Python Pandas - Alter index name


To alter index name, use the index.rename() method in Pandas. At first, import the required libraries −

import pandas as pd

Creating Pandas index −

index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')

Display the Pandas index −

print("Pandas Index...\n",index)

Rename the index −

print("\nRename the index...\n",index.rename('Mode_of_Transport'))

Example

Following is the code −

import pandas as pd

# Creating Pandas index
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Rename the index
print("\nRename the index...\n",index.rename('Mode_of_Transport'))

Output

This will produce the following output −

Pandas Index...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport')

Number of elements in the index...
6

The dtype object...
object

Rename the index...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Mode_of_Transport')

Updated on: 13-Oct-2021

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements