How to Change One or More Index Values in Pandas

In Pandas, it is possible to change the values of one or more index values by using the indexing operator. This allows the user to select a single row or multiple rows as well as a single column or multiple columns and then modify the values present in the selected index. This can be done by using the .loc method, the .iloc method, or by simply assigning the new values to the selected indices. This allows users to easily update, add, or delete values from their dataframe and manipulate data in various ways.


You can use the following syntax to change a single index value in a pandas DataFrame:

df.rename(index={'Old_Value':'New_Value'}, inplace=True)

And you can use the following syntax to change several index values at once:

df.rename(index={'Old1':'New1', 'Old2':'New2'}, inplace=True)

The following examples shows how to use this syntax in practice.

Example 1: Change One Index Value in Pandas DataFrame

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#make 'team' column the index column
df.set_index('team', inplace=True)

#view DataFrame
df

	points	assists	rebounds
team			
A	25	5	11
B	12	7	8
C	15	7	10
D	14	9	6
E	19	12	6
F	23	9	5
G	25	9	9
H	29	4	12

We can use the following code to replace the ‘A’ value in the index column to be ‘P’ instead:

#replace 'A' with 'P' in index
df.rename(index={'A':'P'}, inplace=True)

#view updated DataFrame
df

        points	assists	rebounds
team			
P	25	5	11
B	12	7	8
C	15	7	10
D	14	9	6
E	19	12	6
F	23	9	5
G	25	9	9
H	29	4	12

Notice that the ‘A’ value in the original index has been replaced while all other values remained the same.

Example 2: Change Multiple Index Values in Pandas DataFrame

Suppose we have the same pandas DataFrame as before:

#view DataFrame
df

	points	assists	rebounds
team			
A	25	5	11
B	12	7	8
C	15	7	10
D	14	9	6
E	19	12	6
F	23	9	5
G	25	9	9
H	29	4	12

We can use the following code to replace the ‘A’ and ‘B’ values in the index column:

#replace 'A' with 'P' and replace 'B' with 'Q' in index
df.rename(index={'A':'P', 'B':'Q'}, inplace=True)

#view updated DataFrame
df

	points	assists	rebounds
team			
P	25	5	11
Q	12	7	8
C	15	7	10
D	14	9	6
E	19	12	6
F	23	9	5
G	25	9	9
H	29	4	12

Notice that the ‘A’ and ‘B’ values in the original index have been replaced while all other values remained the same.

x