Table of Contents
To rename an index in a Pandas DataFrame, use the “rename” method and specify the “index” parameter with the desired new name. This will change the name of the index without altering any data in the DataFrame. It is a useful function for organizing and labeling data in a more meaningful way.
Rename Index in Pandas DataFrame
You can use the following syntax to rename the index column of a pandas DataFrame:
df.index.rename('new_index_name', inplace=True)
The following example shows how to use this syntax in practice.
Example: Rename Index in Pandas DataFrame
Suppose we have the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'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]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
Currently the DataFrame has no index name:
#display index name print(df.index.name) None
We can use df.index.rename() to rename the index:
#rename index df.index.rename('new_index', inplace=True) #view updated DataFrame df points assists rebounds new_index 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12
Note that inplace=True tells pandas to retain all of the original DataFrame properties.
We can verify that the DataFrame now has an index name:
#display index name print(df.index.name) new_index
The following tutorials explain how to perform other common operations in pandas:
Cite this article
stats writer (2024). How can I rename an index in a Pandas DataFrame?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-i-rename-an-index-in-a-pandas-dataframe/
stats writer. "How can I rename an index in a Pandas DataFrame?." PSYCHOLOGICAL SCALES, 2 May. 2024, https://scales.arabpsychology.com/stats/how-can-i-rename-an-index-in-a-pandas-dataframe/.
stats writer. "How can I rename an index in a Pandas DataFrame?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-can-i-rename-an-index-in-a-pandas-dataframe/.
stats writer (2024) 'How can I rename an index in a Pandas DataFrame?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-i-rename-an-index-in-a-pandas-dataframe/.
[1] stats writer, "How can I rename an index in a Pandas DataFrame?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, May, 2024.
stats writer. How can I rename an index in a Pandas DataFrame?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.
