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
Python - Make new Pandas Index with deleting multiple index elements
To create a new Pandas Index by deleting multiple index elements, use the index.delete() method. This method accepts a list of positions to remove and returns a new Index object without modifying the original.
Syntax
Index.delete(loc)
Where loc is an integer, list of integers, or array-like of integers representing positions to delete.
Basic Example
Let's start by creating an index and deleting multiple elements ?
import pandas as pd
# Create an index
index = pd.Index([15, 25, 35, 45, 55, 75, 95])
print("Original Index:")
print(index)
# Delete elements at positions 2 and 4 (values 35 and 55)
new_index = index.delete([2, 4])
print("\nAfter deleting positions 2 and 4:")
print(new_index)
Original Index: Index([15, 25, 35, 45, 55, 75, 95], dtype='int64') After deleting positions 2 and 4: Index([15, 25, 45, 75, 95], dtype='int64')
Deleting Non-consecutive Positions
You can delete elements at any positions, not necessarily consecutive ?
import pandas as pd
# Create a string index
cities = pd.Index(['Tokyo', 'London', 'Paris', 'Berlin', 'Rome', 'Madrid'])
print("Original Index:")
print(cities)
# Delete elements at positions 0, 2, and 5
new_cities = cities.delete([0, 2, 5])
print("\nAfter deleting positions 0, 2, and 5:")
print(new_cities)
Original Index: Index(['Tokyo', 'London', 'Paris', 'Berlin', 'Rome', 'Madrid'], dtype='object') After deleting positions 0, 2, and 5: Index(['London', 'Berlin', 'Rome'], dtype='object')
Using with DataFrame Index
This method is commonly used to remove rows from a DataFrame by modifying its index ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Score': [85, 92, 78, 88, 95]
})
print("Original DataFrame:")
print(df)
# Create new index by deleting positions 1 and 3
new_index = df.index.delete([1, 3])
df_filtered = df.loc[new_index]
print("\nDataFrame after removing rows at positions 1 and 3:")
print(df_filtered)
Original DataFrame:
Name Score
0 Alice 85
1 Bob 92
2 Charlie 78
3 David 88
4 Eve 95
DataFrame after removing rows at positions 1 and 3:
Name Score
0 Alice 85
2 Charlie 78
4 Eve 95
Key Points
- The
delete()method returns a new Index object without modifying the original - Positions are zero-indexed (first element is at position 0)
- You can pass a single integer or a list of integers for multiple deletions
- The method works with any Index type (numeric, string, datetime, etc.)
Conclusion
Use index.delete() with a list of positions to create a new Index by removing multiple elements. This method is particularly useful for filtering DataFrames by removing specific rows based on their positions.
