Để tính hiệu đối xứng (symmetric difference) của hai đối tượng Index, sử dụng phương thức index1.symmetric_difference(index2) trong Pandas. Kết quả mặc định được sắp xếp.
Hiệu đối xứng chứa các phần tử chỉ xuất hiện ở một trong hai Index.
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([40, 10, 60, 20, 55]) - Gọi
index1.symmetric_difference(index2).
Ví dụ hoàn chỉnh
import pandas as pd
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index([40, 10, 60, 20, 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)
# Hiệu đối xứng (mặc định sắp xếp)
res = index1.symmetric_difference(index2)
print("\nThe index1 and index2 symmetric difference...\n", res)
Kết quả
Pandas Index1...
Int64Index([10, 20, 30, 40, 50], dtype='int64')
Pandas Index2...
Int64Index([40, 10, 60, 20, 55], dtype='int64')
Number of elements in index1...
5
Number of elements in index2...
5
The index1 and index2 symmetric difference...
Int64Index([30, 50, 55, 60], dtype='int64')
Giải thích: Chỉ có ở index1: 30, 50. Chỉ có ở index2: 55, 60. Kết quả được sắp xếp tăng dần: [30, 50, 55, 60].