How to Rename Columns in Pandas DataFrame

Need to rename columns in Pandas DataFrame?

If so, you may use the following syntax to rename your column:

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

In the next section, I’ll review 2 examples in order to demonstrate how to rename columns in pandas DataFrames.

Example 1: Rename a Single Column in Pandas DataFrame

Say that you created a DataFrame in Python, but accidentally assigned the wrong column name.

For example, let’s suppose that you 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, columns = ['Vegetables'])

print (df)

And here is the result:

pandas dataframe

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 then use to rename the column:

import pandas as pd

data = {'Vegetables': ['Apple', 'Orange', 'Banana', 'Coconut', 'Mango']}
df = pd.DataFrame(data, columns = ['Vegetables'])

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

print (df)

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

Rename Columns in Pandas DataFrame

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 accidentally 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,columns = ['Colors','Shapes'])

print (df)

And this is the result:

dataframe example in Python

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 = df.rename(columns = {'Colors':'Shapes','Shapes':'Colors'})

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,columns = ['Colors','Shapes'])

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

print (df)

You’ll now get the correct column names:

How to Rename Columns in Pandas DataFrame