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

By using rename_axis(), Index.rename() functions you can rename the row index name/label of a pandas DataFrame. Besides these, there are several ways like df.index.names = ['Index'], rename_axis(), set_index() to rename the index. In this article, I will explain multiple ways of how to rename a single index and multiple indexes of the Pandas DataFrame.

Advertisements

Related: Pandas Rename Column and Pandas Rename or Change Row index Values.

Key Points –

  • Pandas provides the rename_axis() method to rename the index of a DataFrame.
  • This method allows users to change the name of the index without altering the underlying data.
  • Users can specify the new name for the index using the name parameter of the rename_axis() method.
  • Renaming the index can be particularly useful when preparing data for visualization or when exporting data to different formats.
  • The rename_axis() method in Pandas offers a straightforward way to rename the index of a DataFrame without modifying the data itself.
  • Renaming the index can improve the interpretability and clarity of DataFrame operations and analyses.

Quick Examples of Rename DataFrame Index

If you are in a hurry, below are some of the quick examples of renaming Pandas DataFrame index.


# Quick examples of rename dataframe index

# Add/Change name to Index 
# Using df.index.name
df.index.names = ['Index']

# Add/Change name to Index 
# Using df.index.rename()
df.index = df.index.rename('Index')
df.index.rename('Index', inplace=True)

# Add/Change name to Index 
# Using df.rename_axis()
df2 = df.rename_axis('Index')
df.rename_axis('Index', inplace=True)

# DataFrame.rename_axis() 
# To change axis parameter
df2=df2.rename_axis('Attributes', axis='columns')

# Add Multilevel index
# Using set_index() 
df2 = df.set_index(['Courses', 'Duration'], append=True)

# Rename Single index from multi level
df2.index = df2.index.set_names('Courses_Duration', level=2)

# Rename All indexes
df2.index=df2.index.rename(['Index','Courses_Name','Courses_Duration'])

First, let’s create a Pandas 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.

Use rename_axis() to Rename Pandas DataFrame Index

Use DataFrame.rename_axis() to add/rename the column Index. Above DataFrame doesn’t have an Index name and will use this method to add an index label first. Note that this method by default returns a new DataFrame after adding an Index. Use inplace=False to update the existing DataFrame.


# Rename row with index
df1 = df.rename_axis('Index')
print(df1)

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

Another simple way to add/rename an Index is by using DataFrame.index.rename() and df.index.names = [‘Index’]. These update the index on the existing DataFrame.


# Using DataFrame.index.rename to change Index
df.index = df.index.rename('Index')
(or)
df.index.names = ['Index']
print(df)

Now, let’s rename the row Index to New_Index from Index label.


# Rename Index
df2 = df.rename_axis('New_Index')

Also, add a column name to Index.


df2=df2.rename_axis('Attributes', axis='columns')
print(df2)

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

Using DataFrame.set_index()

You can also add multiple indexes using set_index(), pass a list of columns to be set as the indexes. Now, both Courses and Duration are indexes for the DataFrame.


# Add Multilevel index using set_index() 
df2 = df.set_index(['Courses', 'Duration'], append=True)
print(df2)

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

Using index.set_names()

To rename multiple index levels using index.set_names(). For instance, rename the single index level Duration to Courses_Duration in the DataFrame df2.


# Rename Single index from multi Level
df2.index = df2.index.set_names('Courses_Duration', level=2)
print(df2)

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

Rename All indexes

You can rename multiple or all levels of indexes in a DataFrame using the rename_axis() method. Now, all index levels are renamed as Index, Courses_Name, and Courses_Duration.


# Rename All indexes
df2.index=df2.index.rename(['Index','Courses_Name','Courses_Duration'])
print(df2)

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

Complete Example For Rename DataFrame Index


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)

# Add/Change name to index 
# Using df.index.name
df.index.names = ['Index']
print(df)

# Add/Change name to Index 
# Using df.rename_axis()
df1 = df.rename_axis('Index')
print(df1)

# Add/Change name to Index 
# Using df.index.rename()
df.index = df.index.rename('Index')
print(df)

# DataFrame.rename_axis() 
# To change axis parameter
df2 = df.rename_axis('New_Index')
df2=df2.rename_axis('Attributes', axis='columns')
print(df2)

# Add Multilevel index 
# Using set_index() 
df2 = df.set_index(['Courses', 'Duration'], append=True)
print(df2)

# Rename Single index from multi level
df2.index = df2.index.set_names('Courses_Duration', level=2)
print(df2)

# Rename All indexes
df2.index=df2.index.rename(['Index','Courses_Name','Courses_Duration'])
print(df2)

Frequently Asked Questions on Rename Index of DataFrame

Why should I rename the index of a DataFrame?

Renaming the index of a DataFrame can enhance readability and improve clarity in data analysis. It allows you to provide more descriptive labels to the index, making it easier to understand the data.

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

You can rename the index of a DataFrame using the rename_axis() method in Pandas. This method allows you to specify the new name for the index.

Does renaming the index modify the underlying data in the DataFrame?

Renaming the index of a DataFrame using the rename_axis() method does not modify the underlying data in the DataFrame. It only changes the name of the index. The rename_axis() method operates on the labels of the index, not on the data itself. Therefore, it preserves the integrity and contents of the DataFrame while allowing you to provide a more descriptive name for the index.

Can I rename the index to multiple levels in a DataFrame?

You can rename the index to multiple levels, also known as a multi-index or hierarchical index, using the rename_axis() method. This allows for more complex indexing and slicing operations on the DataFrame.

Is it possible to rename the index inplace?

You can rename the index inplace by setting the inplace parameter to True when using the rename_axis() method. This will modify the DataFrame in place without the need to reassign it to a new variable.

Conclusion

In this article, you have learned how to rename pandas DataFrame index using set_axis(), set_index(), index.set_names() and more methods with examples.

Happy Learning !!

Leave a Reply