Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Alter index name
To alter index name in Pandas, use the index.rename() method. This method returns a new Index object with the specified name while keeping all the original data intact.
Syntax
The basic syntax for renaming an index is ?
index.rename(name)
Parameters:
- name ? The new name for the index
Creating a Pandas Index
First, let's create a Pandas Index with an initial name ?
import pandas as pd
# Creating Pandas index with name 'Transport'
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], name='Transport')
# Display the original index
print("Original Pandas Index:")
print(index)
Original Pandas Index: Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport')
Renaming the Index
Now let's rename the index using the rename() method ?
import pandas as pd
# Creating Pandas index
index = pd.Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], name='Transport')
# Rename the index
renamed_index = index.rename('Mode_of_Transport')
print("Original index name:", index.name)
print("Renamed index name:", renamed_index.name)
print("\nRenamed Index:")
print(renamed_index)
Original index name: Transport Renamed index name: Mode_of_Transport Renamed Index: Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Mode_of_Transport')
Complete Example
Here's a comprehensive example showing index properties before and after renaming ?
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...")
print(index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...")
print(index.size)
# Return the dtype of the data
print("\nThe dtype object...")
print(index.dtype)
# Rename the index
print("\nRename the index...")
print(index.rename('Mode_of_Transport'))
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')
Key Points
- The
rename()method creates a new Index object and doesn't modify the original index - Only the name property changes; the data and dtype remain the same
- You can assign the result back to a variable to use the renamed index
Conclusion
Use index.rename() to change the name of a Pandas Index. This method returns a new Index object with the updated name while preserving all original data and properties.
Advertisements
