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.
You can use this exact same syntax to replace as many values as you’d like in the index.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Reset an Index in Pandas DataFrame
How to Set Column as Index in Pandas
How to Convert Index to Column in Pandas