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

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

Để nhận mã danh mục của danh mục này, hãy sử dụng 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ố lượng giá trị (danh mục) giới hạn và thường cố định. Đặt danh mục cho danh mục bằng cách sử dụng tham số "danh mục". Xử lý phân loại theo thứ tự bằng cách sử dụng tham số "có thứ tự". Mã là một mảng các số nguyên là vị trí của các giá trị thực trong mảng danh mục -

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 mã danh mục -

print("\nCategory codes from CategoricalIndex...\n",catIndex.codes)

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
# Codes are an array of integers which are the positions of the actual values in the categories array.
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("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories)

# Get the category codes
print("\nCategory codes from CategoricalIndex...\n",catIndex.codes)

Đầ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')

Category codes from CategoricalIndex...
[0 1 2 3 0 1 2 3]