How to Rename Columns in Pandas DataFrame

To rename a single column in Pandas DataFrame:

df.rename(columns={'old column name': 'new column name'}, inplace=True)

To rename multiple columns in Pandas DataFrame:

df.rename(columns={'old column 1': 'new column 1', 'old column 2': 'new column 2'}, inplace=True)

Example 1: Rename a Single Column in Pandas DataFrame

Let’s say that you created a DataFrame in Python, but assigned the wrong column name.

For example, let’s suppose that you originally assigned the column name of ‘Vegetables’ but the items under that column are actually Fruits!

Here is the code to create the DataFrame with the ‘Vegetables’ column name:

import pandas as pd

data = {'Vegetables': ['Apple', 'Orange', 'Banana', 'Coconut', 'Mango']}

df = pd.DataFrame(data)

print(df)

And here is the result:

  Vegetables
0      Apple
1     Orange
2     Banana
3    Coconut
4      Mango

Realizing that you assigned the wrong column name, you decided to rename the column from ‘Vegetables’ to ‘Fruits.’

This is the code that you may use to rename the column:

import pandas as pd

data = {'Vegetables': ['Apple', 'Orange', 'Banana', 'Coconut', 'Mango']}

df = pd.DataFrame(data)

df.rename(columns={'Vegetables': 'Fruits'}, inplace=True)

print(df)

As you can see, the column name is now ‘Fruits’:

    Fruits
0    Apple
1   Orange
2   Banana
3  Coconut
4    Mango

Example 2: Rename Multiple Columns in Pandas DataFrame

Now what if you want rename multiple columns in your Pandas DataFrame?

For example, let’s say that you originally assigned the wrong column names for two columns in your DataFrame:

  • The column name of ‘Colors’ contained a list of shapes
  • The column name of ‘Shapes’ contained a list of colors

This is how the DataFrame looks like:

import pandas as pd

data = {'Colors': ['Triangle', 'Square', 'Circle'],
        'Shapes': ['Red', 'Blue', 'Green']
        }

df = pd.DataFrame(data)

print(df)

And this is the result:

     Colors Shapes
0  Triangle    Red
1    Square   Blue
2    Circle  Green

The concept to rename multiple columns in Pandas DataFrame is similar to that under example one. You just need to separate the renaming of each column using a comma:

df.rename(columns={'Colors': 'Shapes', 'Shapes': 'Colors'}, inplace=True)

So this is the full Python code to rename the columns:

import pandas as pd

data = {'Colors': ['Triangle', 'Square', 'Circle'],
        'Shapes': ['Red', 'Blue', 'Green']
        }

df = pd.DataFrame(data)

df.rename(columns={'Colors': 'Shapes', 'Shapes': 'Colors'}, inplace=True)

print(df)

You’ll now get the correct column names:

     Shapes Colors
0  Triangle    Red
1    Square   Blue
2    Circle  Green