Pandas DataFrame rename_axis() Method – Explained with Examples

The rename_axis() method in Pandas is a powerful tool for renaming the axes(row and/or column) of a DataFrame. In this blog, we will explore how to use the rename_axis() method with various examples to demonstrate its flexibility and usefulness.

Syntax of rename_axis()
Python
DataFrame.rename_axis(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False)
  • mapper: Dictionary or function to apply to the axis labels.
  • index: Alternative to mapper for specifying the index.
  • columns: Alternative to mapper for specifying the columns.
  • axis: Axis to target with mapper (0 or ‘index’, 1 or ‘columns’).
  • copy: Also copy underlying data.
  • inplace: Whether to modify the DataFrame in place (default is False).
Basic Usage

Let’s start with a basic example of how to use rename_axis() to rename the index and column labels of a DataFrame.

Python
import pandas as pd

# Creating a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
}, index=['a', 'b', 'c'])

print("Original DataFrame:")
print(df)

# Renaming the index and columns
df_renamed = df.rename_axis(index='Index', columns='Columns')

print("\nDataFrame after renaming axis labels:")
print(df_renamed)

Output:

Original DataFrame:
   A  B
a  1  4
b  2  5
c  3  6

DataFrame after renaming axis labels:
Columns    A  B
Index           
a         1  4
b         2  5
c         3  6

In this example, we renamed the index label to “Index” and the column label to “Columns” using rename_axis() method.

Inplace Renaming

To modify the DataFrame in place, set the inplace parameter to True.

Python
# Creating a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
}, index=['a', 'b', 'c'])

print("Original DataFrame:")
print(df)

# Renaming index and columns in place
df.rename_axis(index='Index', columns='Columns', inplace=True)

print("\nDataFrame after renaming axis labels in place:")
print(df)

Output:

Original DataFrame:
   A  B
a  1  4
b  2  5
c  3  6

DataFrame after renaming axis labels in place:
Columns   A  B
Index           
a         1  4
b         2  5
c         3  6

In this example, the DataFrame df is modified in place(modified the original dataframe), and the axis labels are renamed.

Also Explore:

Leave a Comment