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

Python Pandas CategoricalIndex - Kiểm tra categories có thứ tự không


Dùng thuộc tính ordered của CategoricalIndex kiểm tra categories có được sắp xếp (có quan hệ so sánh) hay không.

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

1. Import thư viện

import pandas as pd

2. Tạo CategoricalIndex ordered

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

3. Hiển thị CategoricalIndex

print("Categorical Index...\n", catIndex)

4. Kiểm tra ordered

print("\nCategories có ordered?\n", catIndex.ordered)

Ví dụ hoàn chỉnh

import pandas as pd

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

print("Categorical Index...\n", catIndex)
print("\nCategories...\n", catIndex.categories)
print("\nCategories có ordered?\n", catIndex.ordered)

Kết quả đầu ra

Categorical Index...
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'],
                 categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
Categories...
Index(['p', 'q', 'r', 's'], dtype='object')
Categories có ordered?
True

Lưu ý: ordered=True cho phép so sánh <, >, <=, >= giữa các phần tử theo thứ tự categories. ordered=False chỉ cho phép ==, !=.