How to change column names in pandas Dataframe using a list of names?

Viewed 69109

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.

5 Answers

you could use

df.columns = ['Leader', 'Time', 'Score']

If you need rename (l is your list of name need to change to)

df.rename(columns=dict(zip(df.columns,l)))

Just update the columns attribute:

df.columns = list_of_names

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.


Why not just modify df.columns directly?

The accepted answer is fine and is used often, but set_axis has some advantages:

  1. 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()
    
  2. set_axis should theoretically provide better error checking than directly modifying an attribute, though I can't find a specific example at the moment.

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

Related