CategoricalIndex의 범주를 순서형으로 설정하기
Pandas에서 CategoricalIndex의 범주를 순서형(ordered) 상태로 만들려면 as_ordered() 메서드를 사용하면 됩니다. 이 메서드를 호출하면 범주형 인덱스의 ordered 속성이 True로 변경되어, 범주 간 대소 비교나 지정된 순서에 따른 정렬이 가능해집니다.
1단계: 필요한 라이브러리 임포트
먼저 pandas 라이브러리를 임포트합니다.
import pandas as pd
2단계: CategoricalIndex 생성 및 범주 설정
"categories" 매개변수를 사용하여 범주형 인덱스의 카테고리를 지정합니다.
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], categories=["p", "q", "r", "s"])
3단계: 설정된 범주 확인
현재 설정된 카테고리 목록을 출력하여 확인합니다.
print("\nCategoricalIndex의 범주 표시...\n", catIndex.categories)4단계: as_ordered()로 순서형 변환
as_ordered() 메서드를 호출하여 범주를 순서형으로 설정합니다.
print("\nCategoricalIndex 순서형 변환...\n", catIndex.as_ordered())전체 예제 코드
다음은 지금까지의 과정을 하나로 정리한 전체 코드입니다.
import pandas as pd
# "categories" 매개변수를 사용하여 범주 설정
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], categories=["p", "q", "r", "s"])
# CategoricalIndex 출력
print("CategoricalIndex...\n", catIndex)
# 범주 확인
print("\nCategoricalIndex의 범주 표시...\n", catIndex.categories)
# 범주를 순서형(ordered)으로 설정
print("\nCategoricalIndex 순서형 변환...\n", catIndex.as_ordered())실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=False, dtype='category') CategoricalIndex의 범주 표시... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex 순서형 변환... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
핵심 포인트
실행 결과를 살펴보면, as_ordered() 메서드 호출 전에는 ordered=False였지만 호출 후에는 ordered=True로 변경된 것을 확인할 수 있습니다. 범주가 순서형으로 지정되면 <, > 같은 비교 연산자로 범주 값 간의 대소 관계를 판단할 수 있으며, 데이터 정렬 시에도 범주에 지정된 순서가 기준으로 적용됩니다.