Reputation: 917
I have been trying to change the column names of a pandas dataframe using a list of names. The following code is being used:
df.rename(columns = list_of_names, inplace=True)
However I got a Type Error each time, with an error message that says "list object is not callable". I would like to know why does this happen? And What can I do to solve this problem? Thank you for your help.
Upvotes: 29
Views: 88314
Reputation: 27
I would check your df declarations. I had this issue recently and I had actually mistakenly declared the variable as df=[]
. It took me a minute to figure out that I mistakenly was making it a list/array instead of a Dataframe.
Upvotes: 0
Reputation: 41327
set_axis
To set column names, use set_axis
along axis=1
or axis='columns'
:
df = df.set_axis(list_of_names, axis=1)
Note that the default axis=0
sets index names.
df.columns
directly?The accepted answer is fine and is used often, but set_axis
has some advantages:
set_axis
allows method chaining:
df.some_method().set_axis(list_of_names, axis=1).another_method()
vs:
df = df.some_method()
df.columns = list_of_names
df.another_method()
set_axis
should theoretically provide better error checking than directly modifying an attribute, though I can't find a specific example at the moment.
Upvotes: 7
Reputation: 106
if your list is : column_list so column_list
is ['a', 'b', 'c']
and original df.columns
is ['X', 'Y', 'Z']
you just need: df.columns = column_list
Upvotes: 1
Reputation: 323226
If you need rename
(l
is your list of name need to change to)
df.rename(columns=dict(zip(df.columns,l)))
Upvotes: 13