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

Python Pandas - Giao (Intersection) của hai Index và sắp xếp kết quả

Để thực hiện phép giao (intersection) của hai Index và sắp xếp kết quả, sử dụng phương thức index1.intersection(index2, sort=None). Tham số sort=None (mặc định) sẽ sắp xếp kết quả nếu có thể.

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([4, 3, 2, 1]), index2 = pd.Index([8, 2, 6, 4])
  3. Gọi index1.intersection(index2, sort=None).

Ví dụ hoàn chỉnh

import pandas as pd

index1 = pd.Index([4, 3, 2, 1])
index2 = pd.Index([8, 2, 6, 4])

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, sắp xếp kết quả
res = index1.intersection(index2, sort=None)
print("\nThe index1 and index2 intersection (sorted result)...\n", res)

Kết quả

Pandas Index1...
 Int64Index([4, 3, 2, 1], dtype='int64')
Pandas Index2...
 Int64Index([8, 2, 6, 4], dtype='int64')
Number of elements in index1...
 4
Number of elements in index2...
 4
The index1 and index2 intersection (sorted result)...
 Int64Index([2, 4], dtype='int64')

Giải thích: Phần tử chung: 2 và 4. Kết quả được sắp xếp tăng dần: [2, 4].