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 passed location deleted
To make new Pandas Index with passed location deleted, use the index.delete() method. This method creates a new Index object with the specified position removed, leaving the original Index unchanged.
Syntax
The syntax of the Parameters: Here's how to delete a single element from a Pandas Index ? You can also delete multiple elements by passing a list of positions ? Here's a comprehensive example showing various operations with the delete method ? The delete()
Index.delete(loc)
Deleting a Single Element
import pandas as pd
# Creating the index
index = pd.Index([15, 25, 35, 45, 55])
# Display the original index
print("Original Pandas Index...")
print(index)
# Delete element at position 2 (3rd element: 35)
new_index = index.delete(2)
print("\nAfter deleting element at position 2...")
print(new_index)
Original Pandas Index...
Index([15, 25, 35, 45, 55], dtype='int64')
After deleting element at position 2...
Index([15, 25, 45, 55], dtype='int64')
Deleting Multiple Elements
import pandas as pd
# Creating the index
index = pd.Index(['A', 'B', 'C', 'D', 'E'])
print("Original Index:")
print(index)
# Delete elements at positions 1 and 3
new_index = index.delete([1, 3])
print("\nAfter deleting positions 1 and 3:")
print(new_index)
Original Index:
Index(['A', 'B', 'C', 'D', 'E'], dtype='object')
After deleting positions 1 and 3:
Index(['A', 'C', 'E'], dtype='object')
Complete Example
import pandas as pd
# Creating the index
index = pd.Index([15, 25, 35, 45, 55])
# Display the 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 a tuple of the shape of the underlying data
print("\nA tuple of the shape of underlying data...")
print(index.shape)
# Deleting a single index at 3rd position i.e. index 2
print("\nRemaining Index after deleting an index at location 3rd (index 2)...")
print(index.delete(2))
Pandas Index...
Index([15, 25, 35, 45, 55], dtype='int64')
Number of elements in the index...
5
A tuple of the shape of underlying data...
(5,)
Remaining Index after deleting an index at location 3rd (index 2)...
Index([15, 25, 45, 55], dtype='int64')
Key Points
delete() method returns a new Index objectConclusion
delete() method provides an easy way to create a new Pandas Index with specific elements removed. It's useful for data cleaning and index manipulation tasks while preserving the original Index structure.
