Changing a specific column name in pandas DataFrame [duplicate]

I was looking for an elegant way to change a specified column name in a DataFrame.

play data ...

import pandas as pd
d = {
         'one': [1, 2, 3, 4, 5],
         'two': [9, 8, 7, 6, 5],
         'three': ['a', 'b', 'c', 'd', 'e']
    }
df = pd.DataFrame(d)

The most elegant solution I have found so far ...

names = df.columns.tolist()
names[names.index('two')] = 'new_name'
df.columns = names

I was hoping for a simple one-liner ... this attempt failed ...

df.columns[df.columns.tolist().index('one')] = 'another_name'

Any hints gratefully received.


Solution 1:

A one liner does exist:

In [27]: df=df.rename(columns = {'two':'new_name'})

In [28]: df
Out[28]: 
  one three  new_name
0    1     a         9
1    2     b         8
2    3     c         7
3    4     d         6
4    5     e         5

Following is the docstring for the rename method.

Definition: df.rename(self, index=None, columns=None, copy=True, inplace=False)
Docstring:
Alter index and / or columns using input function or
functions. Function / dict values must be unique (1-to-1). Labels not
contained in a dict / Series will be left as-is.

Parameters
----------
index : dict-like or function, optional
    Transformation to apply to index values
columns : dict-like or function, optional
    Transformation to apply to column values
copy : boolean, default True
    Also copy underlying data
inplace : boolean, default False
    Whether to return a new DataFrame. If True then value of copy is
    ignored.

See also
--------
Series.rename

Returns
-------
renamed : DataFrame (new object)

Solution 2:

Since inplace argument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:

df.rename(columns={'two':'new_name'}, inplace=True)