Để tính hiệu đối xứng (symmetric difference) của hai Index và không sắp xếp kết quả, sử dụng phương thức symmetric_difference() với tham số sort=False.
Hiệu đối xứng chứa các phần tử chỉ xuất hiện ở một trong hai Index (không có trong cả hai).
Các bước thực hiện
- Import thư viện:
import pandas as pd - Tạo hai Index:
index1 = pd.Index([50, 30, 20, 40, 10]),index2 = pd.Index([40, 10, 60, 20, 55]) - Gọi
index1.symmetric_difference(index2, sort=False).
Ví dụ hoàn chỉnh
import pandas as pd
index1 = pd.Index([50, 30, 20, 40, 10])
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, không sắp xếp kết quả
res = index1.symmetric_difference(index2, sort=False)
print("\nThe index1 and index2 symmetric difference with unsorted result...\n", res)
Kết quả
Pandas Index1...
Int64Index([50, 30, 20, 40, 10], 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 with unsorted result...
Int64Index([50, 30, 60, 55], dtype='int64')
Giải thích: Phần tử chỉ có ở index1: 50, 30. Phần tử chỉ có ở index2: 60, 55. Với sort=False, thứ tự giữ theo thứ tự xuất hiện ban đầu.