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 - Make new Index with passed list of labels deleted
To make a new Index with passed list of labels deleted, use the index.drop() method. This method returns a new Index object with specified labels removed, leaving the original Index unchanged.
Syntax
Index.drop(labels, errors='raise')
Parameters
labels − Single label or list of labels to be dropped
errors − If 'ignore', suppress error and only existing labels are dropped
Creating a Pandas Index
First, let's create a basic Index with vehicle names ?
import pandas as pd
# Creating the index
index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])
# Display the index
print("Original Pandas Index...")
print(index)
Original Pandas Index... Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'], dtype='object')
Dropping Single Label
Drop a single label from the Index ?
import pandas as pd
index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])
# Drop single label
new_index = index.drop('Bike')
print("After dropping 'Bike':")
print(new_index)
After dropping 'Bike': Index(['Car', 'Truck', 'Ship', 'Airplane'], dtype='object')
Dropping Multiple Labels
Drop multiple labels by passing a list ?
import pandas as pd
index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])
# Drop multiple labels
new_index = index.drop(['Bike', 'Ship'])
print("After dropping ['Bike', 'Ship']:")
print(new_index)
print(f"\nOriginal index shape: {index.shape}")
print(f"New index shape: {new_index.shape}")
After dropping ['Bike', 'Ship']: Index(['Car', 'Truck', 'Airplane'], dtype='object') Original index shape: (5,) New index shape: (3,)
Error Handling
Use the errors parameter to handle non-existent labels ?
import pandas as pd
index = pd.Index(['Car', 'Bike', 'Truck', 'Ship', 'Airplane'])
# Drop with error handling
try:
# This would raise KeyError
new_index = index.drop(['Bike', 'Bus'])
except KeyError as e:
print(f"KeyError: {e}")
# Ignore errors for non-existent labels
new_index = index.drop(['Bike', 'Bus'], errors='ignore')
print("\nWith errors='ignore':")
print(new_index)
KeyError: "['Bus'] not found in axis" With errors='ignore': Index(['Car', 'Truck', 'Ship', 'Airplane'], dtype='object')
Conclusion
The drop() method creates a new Index with specified labels removed. Use errors='ignore' to handle non-existent labels gracefully. The original Index remains unchanged.
Advertisements
