Để tạo Index dựa trên Categorical nền, sử dụng phương thức pandas.CategoricalIndex().
Trước tiên, import thư viện:
import pandas as pd
CategoricalIndex là Index dựa trên Categorical. Chỉ nhận số lượng hữu hạn các giá trị. Thiết lập danh mục bằng categories, thứ tự bằng 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
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
print("Categorical Index...\n", catIndex)
print("\nHiển thị danh mục từ CategoricalIndex...\n", catIndex.categories)
print("\nGiá trị nhỏ nhất từ CategoricalIndex...\n", catIndex.min())
print("\nGiá trị lớn nhất từ CategoricalIndex...\n", catIndex.max())
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') Giá trị nhỏ nhất từ CategoricalIndex... p Giá trị lớn nhất từ CategoricalIndex... s