nostradukemas
nostradukemas

Reputation: 317

Renaming Pandas DataFrame columns that are numbers

I have a DataFrame that has integers for column names that looks like this:

      1     2     3     4
 Red  7     3     2     9
 Blue 3     1     6     4

I'd like to rename the columns. I tried using the following

df = df.rename(columns={'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four'})

However that doesn't change the column names. Do I need to do something else to change column names when they are numbers?

Upvotes: 6

Views: 4690

Answers (3)

sameera lakshitha
sameera lakshitha

Reputation: 1971

You can use two way to change columns name in Pandas DataFrame.

  1. Changing the column name using df.columns attribute.

    df.columns = ['One', 'Two', 'Three', 'Four']

  2. Using rename() function

    df = df.rename(columns={1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'})

Upvotes: 1

bzu
bzu

Reputation: 1594

You need to remove the quotes:

df = df.rename(columns={1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'})

Upvotes: 3

lmiguelvargasf
lmiguelvargasf

Reputation: 69705

What if you use the following:

>>> df.columns = ['One', 'Two', 'Three', 'Four']
>>> df
    One Two Three   Four
0   7   3   6       9
1   3   1   2       4

Upvotes: 1

Related Questions