How to Rename Index in pandas: Simple Guide with Examples
To rename the index in pandas, use the
rename() method on the DataFrame with the index parameter specifying a mapping of old to new index labels. You can also rename the index axis label using df.index.name.Syntax
The main way to rename index labels in pandas is using the rename() method with the index argument. You pass a dictionary mapping old index names to new ones.
df.rename(index={'old_label': 'new_label'}): Renames specific index labels.df.index.name = 'new_name': Changes the name of the index axis (the label shown above the index).
python
df.rename(index={'old_label': 'new_label'}, inplace=True)
df.index.name = 'new_index_name'Example
This example shows how to rename specific index labels and how to set a new name for the index axis.
python
import pandas as pd # Create a sample DataFrame data = {'A': [10, 20, 30], 'B': [100, 200, 300]} df = pd.DataFrame(data, index=['x', 'y', 'z']) # Rename index label 'x' to 'alpha' and 'z' to 'gamma' df.rename(index={'x': 'alpha', 'z': 'gamma'}, inplace=True) # Rename the index axis name df.index.name = 'letters' print(df)
Output
A B
letters
alpha 10 100
y 20 200
gamma 30 300
Common Pitfalls
One common mistake is forgetting to use inplace=True or to assign the result back to a variable, so the rename does not persist.
Another is confusing renaming index labels with renaming columns.
python
import pandas as pd df = pd.DataFrame({'A': [1, 2]}, index=['a', 'b']) # Wrong: rename without inplace or assignment df.rename(index={'a': 'alpha'}) print(df) # Right: use inplace=True or assign df.rename(index={'a': 'alpha'}, inplace=True) print(df)
Output
A
a 1
b 2
A
alpha 1
b 2
Quick Reference
| Action | Code Example | Description |
|---|---|---|
| Rename specific index labels | df.rename(index={'old': 'new'}, inplace=True) | Change one or more index labels. |
| Rename index axis name | df.index.name = 'new_name' | Set or change the name of the index axis. |
| Rename columns (for comparison) | df.rename(columns={'old': 'new'}, inplace=True) | Change column names, not index. |
Key Takeaways
Use df.rename(index={old:new}, inplace=True) to rename index labels.
Set df.index.name to rename the index axis label.
Always use inplace=True or assign the result to keep changes.
Renaming index labels is different from renaming columns.
Check your DataFrame after renaming to confirm changes.