Để lấy các danh mục (categories) của một categorical trong Pandas, ta sử dụng thuộc tính categories của đối tượng CategoricalIndex. Trước tiên, hãy import thư viện cần thiết:
import pandas as pd
CategoricalIndex chỉ có thể nhận một số lượng hữu hạn, thường là cố định, các giá trị có thể (danh mục). Thiết lập các danh mục cho categorical bằng tham số categories. Xử lý categorical theo thứ tự bằng tham số ordered:
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
Hiển thị Categorical Index:
print("Categorical Index...\n", catIndex)
Lấy các danh mục:
print("\nHiển thị danh mục từ CategoricalIndex...\n", catIndex.categories)
Ví dụ hoàn chỉnh
import pandas as pd
# CategoricalIndex chỉ nhận số lượng hữu hạn các giá trị có thể
# Thiết lập danh mục bằng tham số "categories"
# Xử lý theo thứ tự bằng tham số "ordered"
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
# Hiển thị Categorical Index
print("Categorical Index...\n", catIndex)
# Lấy các danh mục
print("\nHiển thị danh mục từ CategoricalIndex...\n", catIndex.categories)
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') Hiển thị danh mục từ CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object')