Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas CategoricalIndex - Nhận các danh mục của phân loại này

Để nhận các danh mục của danh mục này, hãy sử dụng danh mục thuộc tính của CategoricalIndex ở gấu trúc. Đầu tiên, hãy nhập các thư viện được yêu cầu -

import pandas as pd

CategoricalIndex chỉ có thể nhận một số giá trị giới hạn và thường cố định, có thể có (danh mục. Đặt danh mục cho danh mục bằng cách sử dụng thông số "danh mục". Xử lý danh mục theo thứ tự bằng cách sử dụng tham số "đã sắp xếp" -

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

Hiển thị Chỉ mục Phân loại -

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

Nhận các danh mục -

print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)

Ví dụ

Sau đây là mã -

import pandas as pd

# CategoricalIndex can only take on a limited, and usually fixed, number of possible values
# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

# Display the Categorical Index
print("Categorical Index...\n",catIndex)

# Get the categories
print("\nDisplaying Categories from CategoricalIndex...\n",catIndex.categories)

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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

DisplayingCategories from CategoricalIndex...
Index(['p', 'q', 'r', 's'], dtype='object')