How to rename a dataframe index in pandas ?

Published: February 20, 2021

Tags: Python; Pandas; DataFrame;

DMCA.com Protection Status

Examples of how to rename a dataframe index in pandas:

Create a dataframe

Let's first create a simple dataframe with pandas

import pandas as pd
import numpy as np

data = np.random.randint(10, size=(3,3))

columns = ['Score A','Score B','Score C']
index = ['John','Bob','Emma']

df = pd.DataFrame(data=data,index=index,columns=columns)

print(df)

returns for example

      Score A  Score B  Score C
John        0        1        9
Bob         3        8        8
Emma        1        1        4

Note: to get the index names just enter:

df.index

returns here

Index(['John', 'Bob', 'Emma'], dtype='object')

Rename one index name

To rename the name of one index, a solution is to use pandas.DataFrame.rename:

df.rename(index={'Bob': 'Robert'}, inplace=True)

print(df)

returns

            Score A  Score B  Score C
Johnny        0        1        9
Robert        3        8        8
Emma          1        1        4

Rename multiple index names

Another example replace multiple names:

new_index = {'John':'Johnny',
            'Bob':'Robert',
            'Emma':'Emma'}

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

print(df)

        Score A  Score B  Score C
Johnny        0        1        9
Robert        3        8        8
Emma          1        1        4

Note: another solution:

df.index = ['Johnny', 'Robert', 'Emma']

aslo returns

        Score A  Score B  Score C
Johnny        0        1        9
Robert        3        8        8
Emma          1        1        4

References