• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:15 mins read
You are currently viewing Pandas Rename Index Values of DataFrame

To rename index values of pandas DataFrame use rename() method or index attribute. In this article, I will explain multiple ways of how to rename a single index value and multiple index values of the pandas DataFrame using functions like DataFrame.rename(), DataFrame.index property with examples. When you update multiple row index values, you would need to create a Dict with key-value pair and use it with rename() function.

Related: pandas Rename Column of DataFrame & pandas rename Index Name

Key Points –

  • Pandas offers the rename() method for altering index values within a DataFrame.
  • The rename() function facilitates the renaming process through various parameters like index, columns, and level.
  • Renaming index values is pivotal for enhancing data interpretation, ensuring consistency, and aligning with analytical objectives.
  • Utilizing rename() allows for seamless transformation of index labels without altering the underlying data.
  • Renaming index values aids in improving data clarity, consistency, and facilitates effective data analysis without altering the underlying data structure.

1. Quick Examples of Rename Index Values of DataFrame

If you are in a hurry, below are some quick examples of how to rename index values of DataFrame.


# Below are the quick examples

# Assign Indexs to DataFrame.index
df.index = ['index_1', 'index_2', 'index_3', 'index_4']

# Using DataFrame.rename() to rename index values
df2 = df.rename(index={'r3': 'Index_3'})

# Rename multiple index value
df2 = df.rename(index={'r1':'Index_1','r2':'Index_2'})

# Changing the DataFrame inplace
df.rename(index={'r3': 'Index_3','r4': 'Index_4'}, inplace=True)

# Append a value to DataFrame index row Using lambda function
df2 = df.rename(index=lambda Index: Index+'_Index')

Now, let’s create a DataFrame with a few rows and columns, execute these examples, and validate results. Our DataFrame contains column names Courses, Fee, Duration, and Discount.


# Create DataFrame
import pandas as pd
technologies = {
    'Courses':["Spark","PySpark","Python","pandas"],
    'Fee' :[20000,25000,22000,30000],
    'Duration':['30days','40days','35days','50days'],
    'Discount':[1000,2300,1200,2000]
              }
index_labels=['r1','r2','r3','r4']
df = pd.DataFrame(technologies,index=index_labels)
print(df)

Yields below output.


# Output:
    Courses    Fee Duration  Discount
r1    Spark  20000   30days      1000
r2  PySpark  25000   40days      2300
r3   Python  22000   35days      1200
r4   pandas  30000   50days      2000

2. Changing the Row Index Using DataFrame.index() Attribute

In order to rename/change the values for all row index, create a list with new indexes and assign it to DataFrame.index attribute. Note that If your DataFrame is small and for a huge DataFrame this is not an idle solution.


# Change the row indexes
df.index = ['index_1', 'index_2', 'index_3', 'index_4']
print(df)

Yields below output.


# Output:
         Courses    Fee Duration  Discount
index_1    Spark  20000   30days      1000
index_2  PySpark  25000   40days      2300
index_3   Python  22000   35days      1200
index_4   pandas  30000   50days      2000

3. Rename Specific Index Values

pandas.DataFrame.rename() accepts a dictionary as a param for index values you wanted to rename. So you just pass a dict with key-value pair; the key is an existing index you would like to rename and the value would be your preferred index value. The below examples changes the index to'r3' from 'Index_3'.


# Using DataFrame.rename() to rename index values
df = pd.DataFrame(technologies,index=index_labels)
df2 = df.rename(index={'r3': 'Index_3'})
print(df2)

Yields below output.


# Output:
         Courses    Fee Duration  Discount
r1         Spark  20000   30days      1000
r2       PySpark  25000   40days      2300
Index_3   Python  22000   35days      1200
r4        pandas  30000   50days      2000

4. Rename Multiple Row Indexes

You can also use the same approach to rename multiple index values or all indexes of Pandas DataFrame.


# Rename multiple index value
df = pd.DataFrame(technologies,index=index_labels)
df2 = df.rename(index={'r1':'Index_1','r2':'Index_2'})
print(df2)

Yields below output.


# Output:
         Courses    Fee Duration  Discount
Index_1    Spark  20000   30days      1000
Index_2  PySpark  25000   40days      2300
r3        Python  22000   35days      1200
r4        pandas  30000   50days      2000

5. Change the DataFrame Inplace

DataFrame.rename() takes parameter inplace=True to change the DataFrame inplace. In this case, no new DataFrame is returned, and the return value is None.


# Changing the DataFrame inplace
df = pd.DataFrame(technologies,index=index_labels)
df.rename(index={'r3': 'Index_3','r4': 'Index_4'}, inplace=True)
print(df)

Yields below output.


# Output:
         Courses    Fee Duration  Discount
r1         Spark  20000   30days      1000
r2       PySpark  25000   40days      2300
Index_3   Python  22000   35days      1200
Index_4   pandas  30000   50days      2000

6. Append a Value to DataFrame Index

Another approach would be using the lambda function. The below example add’s ‘_Index’ to all index values. This approach helps you to update/rename all indexes


# Append a value to DataFrame index row Using lambda function
df2 = df.rename(index=lambda Index: Index+'_Index')
print(df2)

Yields below output.


# Output:
          Courses    Fee Duration  Discount
r1_Index    Spark  20000   30days      1000
r2_Index  PySpark  25000   40days      2300
r3_Index   Python  22000   35days      1200
r4_Index   pandas  30000   50days      2000

7. Complete Example For Rename Index Values of DataFrame


import pandas as pd
technologies = {
    'Courses':["Spark","PySpark","Python","pandas"],
    'Fee' :[20000,25000,22000,30000],
    'Duration':['30days','40days','35days','50days'],
    'Discount':[1000,2300,1200,2000]
              }
index_labels=['r1','r2','r3','r4']
df = pd.DataFrame(technologies,index=index_labels)
print(df)

# Change the row indexes
df.index = ['index_1', 'index_2', 'index_3', 'index_4']
print(df)

# Using DataFrame.rename() to rename index values
df2 = df.rename(index={'r3': 'Index_3'})
print(df2)

# Rename multiple index value
df2 = df.rename(index={'r1':'Index_1','r2':'Index_2'})
print(df2)

# Changing the DataFrame inplace
df.rename(index={'r3': 'Index_3','r4': 'Index_4'}, inplace=True)
print(df)

# Append a value to DataFrame index row Using lambda function
df2 = df.rename(index=lambda Index: Index+'_Index')
print(df2)

Frequently Asked Questions on Rename Index Values of Pandas DataFrame

How can I rename the index values of a Pandas DataFrame?

Pandas provides the rename() method which can be applied directly to the DataFrame object. You can specify the new index values using a dictionary-like mapping or a function.

Does renaming index values modify the original DataFrame?

Renaming index values using the rename() method in Pandas does not modify the original DataFrame. Instead, it returns a new DataFrame with the updated index values, leaving the original DataFrame unchanged.

Can I rename index values selectively within a DataFrame?

You can selectively rename index values within a DataFrame using the rename() method in Pandas. By specifying the indices you want to rename and their corresponding new values, you can effectively rename index values selectively without affecting the rest of the DataFrame’s index.

Can I rename index values selectively within a DataFrame?

You can rename index values selectively within a DataFrame in Pandas. By using the rename() method and specifying the indices you want to rename along with their new values, you can effectively rename index values selectively without altering the entire index.

Is it possible to rename both row and column index values simultaneously?

The rename() method allows for renaming both row and column index values simultaneously by specifying the index and columns parameters accordingly.

Conclusion

In this article, you have learned how to rename index values of pandas DataFrame using DataFrame.index, DataFrame.rename() and lambda functions with examples. You have also learned how to rename single and multilevel Index values.

Happy Learning !!

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium

Leave a Reply