Để thực hiện phép giao (intersection) của hai đối tượng Index, sử dụng phương thức index1.intersection(index2) trong Pandas. Kết quả mặc định được sắp xếp.
Các bước thực hiện
- Import thư viện:
import pandas as pd - Tạo hai Index:
index1 = pd.Index([10, 20, 30, 40, 50]),index2 = pd.Index([80, 65, 60, 70, 55]) - Gọi
index1.intersection(index2).
Ví dụ hoàn chỉnh
import pandas as pd
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index([80, 65, 60, 70, 55])
print("Pandas Index1...\n", index1)
print("Pandas Index2...\n", index2)
print("\nNumber of elements in index1...\n", index1.size)
print("\nNumber of elements in index2...\n", index2.size)
# Giao hai Index
res = index1.intersection(index2)
print("\nThe index1 and index2 intersection...\n", res)
Kết quả
Pandas Index1...
Int64Index([10, 20, 30, 40, 50], dtype='int64')
Pandas Index2...
Int64Index([80, 65, 60, 70, 55], dtype='int64')
Number of elements in index1...
5
Number of elements in index2...
5
The index1 and index2 intersection...
Int64Index([], dtype='int64')
Giải thích: Hai Index không có phần tử chung nào → kết quả là Index rỗng.