koliyat9811
koliyat9811

Reputation: 917

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

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

Answers (6)

Trav
Trav

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

tdy
tdy

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.


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.

Upvotes: 7

Livid
Livid

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

BENY
BENY

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

JGC
JGC

Reputation: 6363

Just update the columns attribute:

df.columns = list_of_names

Upvotes: 6

Prakash Palnati
Prakash Palnati

Reputation: 3409

you could use

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

Upvotes: 60

Related Questions