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

Python Pandas CategoricalIndex – categories 속성으로 범주 가져오기

Pandas의 CategoricalIndex에 포함된 범주(categories)를 확인하려면 categories 속성을 사용하면 됩니다. 이 속성은 해당 범주형 인덱스가 가질 수 있는 고유한 값들의 목록을 반환합니다.

1. 라이브러리 임포트

먼저 필요한 라이브러리를 임포트합니다.

import pandas as pd

2. CategoricalIndex 생성

CategoricalIndex는 제한적이며 일반적으로 고정된 개수의 가능한 값(범주)만 가질 수 있습니다.

categories 매개변수를 사용해 범주를 지정하고, ordered 매개변수를 True로 설정하면 순서가 있는(orderd) 범주형으로 취급됩니다.

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

3. CategoricalIndex 및 범주 출력하기

생성한 CategoricalIndex를 화면에 표시합니다.

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

이어서 categories 속성을 통해 범주를 가져옵니다.

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

전체 예제 코드

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

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"])

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

# 범주 가져오기
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

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

출력 결과에서 볼 수 있듯이, catIndex.categories는 중복을 제거한 고유 범주 목록인 ['p', 'q', 'r', 's']를 Index 객체 형태로 반환합니다. 이처럼 categories 속성을 활용하면 범주형 데이터가 어떤 값들로 구성되어 있는지 손쉽게 확인할 수 있습니다.