Renaming axis and index in pandas using rename_axis() and index.rename()

python @ Freshers.in

In pandas, there are often scenarios where you may need to rename the axes or the index of a DataFrame for better clarity or understanding. The rename_axis() and index.rename() methods serve this purpose. In this article, we’ll delve into the details of both methods, supplemented with illustrative examples. Both rename_axis() and index.rename() provide flexibility to set and manage the names of DataFrame axes and indices, which can be crucial for data clarity and interpretation.

DataFrame creation

We’ll start by creating a DataFrame:

import pandas as pd
data = {
    'Name': ['Sachin', 'Ramesh', 'Arjun'],
    'Age': [25, 28, 24],
    'City': ['Mumbai', 'Delhi', 'Bangalore']
}
df = pd.DataFrame(data)
print(df)

Output

     Name  Age       City
0  Sachin   25     Mumbai
1  Ramesh   28      Delhi
2   Arjun   24  Bangalore

Renaming axis using rename_axis()

The rename_axis() method is used to set the name of the axis (either rows or columns).

df = df.rename_axis("ID")
print(df)

Output:

      Name  Age       City
ID                        
0   Sachin   25     Mumbai
1   Ramesh   28      Delhi
2    Arjun   24  Bangalore

For columns:

df = df.rename_axis("Attributes", axis="columns")
print(df)

Output:

   Attributes  Name  Age       City
ID                                 
0       Sachin   25     Mumbai
1       Ramesh   28      Delhi
2        Arjun   24  Bangalore

Renaming index using index.rename()

The index.rename() method allows you to set the name of the index.

df = df.index.rename('Identifier')
print(df)
   Attributes  Name  Age       City
Identifier                         
0       Sachin   25     Mumbai
1       Ramesh   28      Delhi
2        Arjun   24  Bangalore

Renaming axis and index together

You can combine both methods to rename the axis and index simultaneously:

df = df.rename_axis("ID").index.rename('Identifier')
print(df)

Resetting the axis and index names

To remove the names, assign None:

df = df.rename_axis(None, axis='columns').index.rename(None)
print(df)

Output

     Name  Age       City
0  Sachin   25     Mumbai
1  Ramesh   28      Delhi
2   Arjun   24  Bangalore

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Author: user