How to Rename Rows and Columns in Pandas?

Spread the love

The rename() method in pandas allows us to rename rows and columns. We can change the row or column labels using this method.

Examples –

Let’s create a dataframe to work with.

import pandas as pd

data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
       'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
       'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
       'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}

index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

1 . Change the Row or Index labels with rename() method –

Let’s say you want to change the row or index labels. Instead of short month names, you want the full names. We can do this using the rename() method in Pandas. We can use a dictionary to map the row labels and pass it to the index parameter of the rename() method.

# change row or index labels
row_labels = {'Jan':'January',
             'Feb':'Febuary',
             'Mar':'March',
             'Apr':'April',
             'Jul':'July',
             'Aug':'August',
             'Sep':'September',
             'Oct':'October',
             'Nov':'November',
             'Dec':'December'}

df.rename(index= row_labels, inplace=True)
df

2 . Change columns labels using rename() method –

We can also change the columns labels using the columns parameter of the rename() method.

Let’s say we want all column names in lowercase.

# change column labels
col_labels = {'Apple':'apple',
             'Orange':'orange',
             'Banana':'banana',
             'Mango':'mango'}

df.rename(columns= col_labels, inplace=True)
df

Rating: 1 out of 5.

Leave a Reply