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 - Form the Union of two Index objects
To form the Union of two Index objects, use the index1.union(index2) method in Pandas. The union operation combines all unique elements from both indexes and returns them in sorted order.
Syntax
index1.union(index2, sort=None)
Parameters
The union() method accepts the following parameters ?
- index2 ? The second Index object to union with
- sort ? Whether to sort the result (default: None, which sorts if possible)
Creating Index Objects
First, let's create two Pandas Index objects ?
import pandas as pd
# Creating two Pandas index
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index([80, 65, 60, 70, 55])
# Display the Pandas indexes
print("Pandas Index1...")
print(index1)
print("\nPandas Index2...")
print(index2)
Pandas Index1... Index([10, 20, 30, 40, 50], dtype='int64') Pandas Index2... Index([80, 65, 60, 70, 55], dtype='int64')
Performing Union Operation
Now let's perform the union operation to combine both indexes ?
import pandas as pd
# Creating two Pandas index
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index([80, 65, 60, 70, 55])
# Perform union
result = index1.union(index2)
print("Union of both indexes:")
print(result)
print(f"\nTotal elements in union: {len(result)}")
Union of both indexes: Index([10, 20, 30, 40, 50, 55, 60, 65, 70, 80], dtype='int64') Total elements in union: 10
Union with Duplicate Elements
The union operation automatically removes duplicates and maintains unique elements ?
import pandas as pd
# Creating indexes with some common elements
index1 = pd.Index([10, 20, 30, 40])
index2 = pd.Index([30, 40, 50, 60])
print("Index1:", index1.tolist())
print("Index2:", index2.tolist())
# Perform union
result = index1.union(index2)
print("Union (duplicates removed):", result.tolist())
Index1: [10, 20, 30, 40] Index2: [30, 40, 50, 60] Union (duplicates removed): [10, 20, 30, 40, 50, 60]
Key Points
- Union combines all unique elements from both indexes
- Duplicate values are automatically removed
- The result is sorted by default (when possible)
- Both indexes must have compatible data types
Conclusion
The union() method provides an efficient way to combine two Index objects while maintaining uniqueness. It automatically handles duplicates and returns a sorted result containing all distinct elements from both indexes.
Advertisements
