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?
Pandas Rename Single Column If you want to rename a single column, just pass the single key-value pair in the columns dict parameter. The result will be the same if there is a non-matching mapping in the columns dictionary.
You can rename pandas DataFrame column name by index (position) using rename() method or by assigning column name to df. columns. values[index] .
Rename Columns with List using set_axis() Alternatively, you can use DataFrame. set_axis() method to rename columns with list. use inplace=True param to rename columns on the existing DataFrame object.
You need to remove the quotes:
df = df.rename(columns={1: 'One', 2: 'Two', 3: 'Three', 4: 'Four'})
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
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With