Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas CategoricalIndex - 범주 코드(codes)를 가져오는 방법

Pandas의 CategoricalIndex에서 범주 코드(category codes)를 확인하려면 codes 속성을 사용하면 됩니다. 먼저 필요한 라이브러리를 임포트합니다.

import pandas as pd

CategoricalIndex는 제한적이고 대개 고정된 개수의 가능한 값(범주)만 가질 수 있습니다. categories 매개변수를 사용해 범주를 지정하고, ordered 매개변수를 사용해 해당 범주형 데이터를 순서가 있는 것으로 처리할 수 있습니다.

여기서 코드(codes)란 실제 값들이 categories 배열 내에서 위치한 인덱스를 나타내는 정수 배열을 의미합니다.

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

CategoricalIndex 출력하기

생성한 CategoricalIndex를 화면에 표시해 보겠습니다.

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

범주 코드 가져오기

codes 속성을 호출하면 각 값의 범주 코드를 확인할 수 있습니다.

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

전체 예제 코드

지금까지 설명한 내용을 하나로 정리한 전체 코드는 다음과 같습니다.

import pandas as pd

# CategoricalIndex는 제한적이고 고정된 개수의 가능한 값(범주)만 가질 수 있습니다.
# "categories" 매개변수로 범주를 지정합니다.
# "ordered" 매개변수로 순서가 있는 범주형으로 처리합니다.
# codes는 실제 값이 categories 배열에서 위치한 정수 배열입니다.
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])

# CategoricalIndex 출력
print("Categorical Index...\n", catIndex)

# 범주(categories) 출력
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)

# 범주 코드(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')

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

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

정리

출력 결과를 보면 각 값('p', 'q', 'r', 's')이 categories 배열에서 차지하는 위치가 각각 0, 1, 2, 3으로 매핑되어 있는 것을 확인할 수 있습니다. 즉, codes 속성은 범주형 데이터를 정수 형태로 인코딩한 결과를 반환하며, 이를 활용하면 메모리를 절약하거나 머신러닝 모델 입력값으로 변환하는 등 다양한 작업에 유용하게 사용할 수 있습니다.