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

Python Pandas - Kiểm tra hai CategoricalIndex có cùng phần tử không


Dùng phương thức equals() kiểm tra hai CategoricalIndex có chứa cùng các phần tử (cùng thứ tự, cùng categories, cùng ordered) hay không.

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

1. Import thư viện

import pandas as pd

2. Tạo 2 CategoricalIndex giống hệt nhau

catIndex1 = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
                                 ordered=True, categories=["p", "q", "r", "s"])
catIndex2 = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
                                 ordered=True, categories=["p", "q", "r", "s"])

3. Kiểm tra bằng nhau

print("\nHai CategoricalIndex bằng nhau?\n", catIndex1.equals(catIndex2))

Ví dụ hoàn chỉnh

import pandas as pd

catIndex1 = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
                                 ordered=True, categories=["p", "q", "r", "s"])
catIndex2 = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"],
                                 ordered=True, categories=["p", "q", "r", "s"])

print("CategoricalIndex1...\n", catIndex1)
print("\nCategoricalIndex2...\n", catIndex2)
print("\nHai CategoricalIndex bằng nhau?\n", catIndex1.equals(catIndex2))

Kết quả đầu ra

CategoricalIndex1...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
                 categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
CategoricalIndex2...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
                 categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
Hai CategoricalIndex bằng nhau?
True

Lưu ý: equals() so sánh cả values, categories, ordered. Nếu chỉ so sánh giá trị, dùng (catIndex1 == catIndex2).all().