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.
你可以用
df.columns = ['Leader', 'Time', 'Score']
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.
只需更新columns属性:
df.columns = list_of_names
如果需要rename
( l
是您需要更改的名称列表)
df.rename(columns=dict(zip(df.columns,l)))
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.