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 Pandas - Return a new Index with elements of index not in other and get the difference
To return a new Index with elements of index not in other and get the difference, use the index1.difference(index2) method in Pandas. This method performs a set difference operation, returning elements that exist in the first index but not in the second.
Syntax
Index.difference(other, sort=None)
Parameters
The difference() method accepts the following parameters ?
- other ? Index or array-like object to compute difference with
- sort ? Whether to sort the result (None, False, or True)
Basic Example
Let's create two Pandas indexes and find their difference ?
import pandas as pd
# Creating two Pandas indexes
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index([80, 40, 60, 20, 55])
# Display both indexes
print("Pandas Index1...")
print(index1)
print("\nPandas Index2...")
print(index2)
# Get the difference - elements in index1 but not in index2
result = index1.difference(index2)
print("\nDifference (index1 - index2)...")
print(result)
Pandas Index1... Index([10, 20, 30, 40, 50], dtype='int64') Pandas Index2... Index([80, 40, 60, 20, 55], dtype='int64') Difference (index1 - index2)... Index([10, 30, 50], dtype='int64')
String Index Example
The The difference()
import pandas as pd
# Creating string indexes
fruits1 = pd.Index(['apple', 'banana', 'orange', 'grape'])
fruits2 = pd.Index(['banana', 'mango', 'grape', 'kiwi'])
print("Fruits Index1:")
print(fruits1)
print("\nFruits Index2:")
print(fruits2)
# Find fruits in index1 but not in index2
difference = fruits1.difference(fruits2)
print("\nFruits in index1 but not in index2:")
print(difference)
Fruits Index1:
Index(['apple', 'banana', 'orange', 'grape'], dtype='object')
Fruits Index2:
Index(['banana', 'mango', 'grape', 'kiwi'], dtype='object')
Fruits in index1 but not in index2:
Index(['apple', 'orange'], dtype='object')
Key Points
difference() method returns elements present in the calling index but absent in the otherindex1.difference(index2) ? index2.difference(index1)
Conclusion
difference() method is useful for finding unique elements between indexes. It performs a set difference operation, returning elements from the first index that don't exist in the second index.
