기본 범주(Categorical)를 기반으로 인덱스를 생성하려면 pandas.CategoricalIndex() 메서드를 사용하면 됩니다.
CategoricalIndex란?
CategoricalIndex는 내부의 Categorical 객체에 기반한 인덱스입니다. 이 인덱스는 제한적이며 일반적으로 고정된 개수의 가능한 값만 가질 수 있습니다. 예를 들어 성별('남', '여'), 학점('A', 'B', 'C')처럼 값의 종류가 정해져 있는 데이터를 다룰 때 유용합니다.
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
범주형 인덱스 만들기
categories 매개변수를 사용해 범주의 카테고리를 지정하고, ordered 매개변수를 사용해 해당 범주를 순서가 있는(ordered) 범주로 취급할 수 있습니다.
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)생성된 Categorical 인덱스를 출력해 보겠습니다.
print("Categorical Index...\n", catIndex)인덱스에 설정된 카테고리 목록을 확인합니다.
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)전체 예제 코드
다음은 지금까지 설명한 내용을 모두 포함한 전체 코드입니다. 여기에 최솟값(min)과 최댓값(max)을 구하는 부분도 추가했습니다.
import pandas as pd
# CategoricalIndex는 내부의 Categorical에 기반한 인덱스입니다.
# categories 매개변수로 범주의 카테고리를 지정하고,
# ordered 매개변수로 순서가 있는 범주로 취급합니다.
catIndex = pd.CategoricalIndex(
["p", "q", "r", "s", "p", "q", "r", "s"],
ordered=True,
categories=["p", "q", "r", "s"]
)
# Categorical 인덱스 출력
print("Categorical Index...\n", catIndex)
# 카테고리 목록 확인
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# 최솟값 구하기
print("\nMinimum value from CategoricalIndex...\n", catIndex.min())
# 최댓값 구하기
print("\nMaximum value from CategoricalIndex...\n", catIndex.max())실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
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') Minimum value from CategoricalIndex... p Maximum value from CategoricalIndex... s
정리
ordered=True로 설정했기 때문에 min()과 max() 같은 순서 비교 연산이 정상적으로 동작합니다. 만약 ordered=False로 생성하면 최솟값·최댓값을 구할 때 TypeError가 발생하므로 주의해야 합니다. 이처럼 CategoricalIndex는 반복되는 한정된 값들로 이루어진 데이터를 효율적으로 관리하고 그룹화할 때 매우 유용한 도구입니다.