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

Python Pandas CategoricalIndex – 범주에 순서 관계가 있는지 확인하는 방법

Pandas의 CategoricalIndex에서 범주(category)들이 순서(ordered) 관계를 가지는지 확인하려면 ordered 속성을 사용하면 됩니다. 이 속성은 해당 범주형 인덱스가 순서가 지정된 카테고리인지 여부를 True 또는 False로 반환합니다.

1. 라이브러리 가져오기

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

import pandas as pd

2. 순서가 있는 CategoricalIndex 생성하기

categories 매개변수로 범주를 설정하고, ordered 매개변수를 True로 지정하여 순서가 있는 범주형 인덱스를 만듭니다.

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

3. CategoricalIndex 출력하기

생성된 범주형 인덱스를 화면에 표시합니다.

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

4. 범주 목록 확인하기

categories 속성으로 인덱스에 포함된 범주들을 확인할 수 있습니다.

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

5. 순서 관계 여부 확인하기

ordered 속성을 사용해 범주 간에 순서 관계가 존재하는지 검사합니다.

print("\nDoes categories have ordered relationship...\n", catIndex.ordered)

전체 예제 코드

다음은 위 과정을 하나로 정리한 전체 코드입니다.

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

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

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

# 범주의 순서 관계 여부 확인
print("\nDoes categories have ordered relationship...\n", catIndex.ordered)

실행 결과

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

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

Does categories have ordered relationship...
True

출력 결과에서 볼 수 있듯이, ordered=True로 생성된 CategoricalIndex의 ordered 속성은 True를 반환합니다. 반대로 순서를 지정하지 않고 생성한 경우에는 False가 반환되므로, 이 속성을 활용하면 범주형 데이터의 순서 여부를 손쉽게 판별할 수 있습니다.