Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Pandas CategoricalIndex - 이 범주의 범주 코드를 가져옵니다.

<시간/>

이 카테고리의 카테고리 코드를 얻으려면 코드를 사용하세요. CategoricalIndex 속성 판다에서. 먼저 필요한 라이브러리를 가져옵니다 -

import pandas as pd

CategoricalIndex는 제한된 수의 가능한 값(범주)만 일반적으로 고정할 수 있습니다. "categories" 매개변수를 사용하여 범주에 대한 범주를 설정합니다. "ordered" 매개변수를 사용하여 범주형을 순서대로 처리합니다. 코드는 범주 배열에서 실제 값의 위치인 정수 배열입니다. -

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

범주형 인덱스 표시 -

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

카테고리 코드 가져오기 -

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

예시

다음은 코드입니다 -

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)

출력

이것은 다음과 같은 출력을 생성합니다 -

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]