Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Hợp (Union) của hai Index nhưng không sắp xếp kết quả

Để thực hiện phép hợp (union) của hai Index và không sắp xếp kết quả, sử dụng phương thức index1.union(index2, sort=False). Lưu ý: tiêu đề gốc nhầm ghi "intersection" nhưng code dùng union.

Các bước thực hiện

  1. Import thư viện: import pandas as pd
  2. Tạo hai Index: index1 = pd.Index([10, 20, 30, 40, 50]), index2 = pd.Index([80, 65, 60, 70, 55])
  3. Gọi index1.union(index2, sort=False).

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)

# Hợp hai Index, không sắp xếp kết quả
res = index1.union(index2, sort=False)
print("\nThe index1 and index2 Union with unsorted result...\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 Union with unsorted result...
 Int64Index([10, 20, 30, 40, 50, 80, 65, 60, 70, 55], dtype='int64')

Giải thích: Kết quả giữ thứ tự: trước toàn bộ index1, sau đó các phần tử của index2 chưa có trong index1. Không có phần tử trùng lặp giữa hai index này.