Reputation: 317
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
Reputation: 1971
You can use two way to change columns name in Pandas DataFrame.
Changing the column name using df.columns attribute.
df.columns = ['One', 'Two', 'Three', 'Four']
Using rename() function
df = df.rename(columns={1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'})
Upvotes: 1
Reputation: 1594
You need to remove the quotes:
df = df.rename(columns={1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'})
Upvotes: 3
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