How to change the name of specific column in Pandas Dataframe



I have read a csv file in pandas dataframe. But the column name of a specific column is not so relevant and thus I want to change it from ;
‘id’ to 'identity’
How can we do it?


We can do above using df.rename() function as follows:
Let df be dataframe . We want to change the name of one of its column from ‘id’ to ‘identity’

df = df.rename(columns({ ‘id’ : ‘identity’})



But what to do in case of default column names.
For eg: I read a csv files with no column names and header = None. (Default column names are 0,1,2,3 etc…)
Now i want to rename one specific column as ‘xyz’.
Can anyone please help in this?



you can re-assign the columns in below fashion (it will work for both default columns 0,1, 2 etc or existing columns)

df.columns =[‘col1’, ‘col2’, ‘col3’]

Hope this helps!


Thanks Kumud for replying, if you could help one more time please.
I have 40 columns and want to rename the last column. Any idea how i can rename the last one without having to write down all 39 before it.


@nirvana.0311 If you want to rename a particular column say (40th column, whose default value is 39), you can do by following below:

df.rename(columns ={39: ‘col40’}, inplace =True).


Thanks kumud… Works like a charm
I had tried similar before, wonder why didn’t it work.