Pandas의 remove_categories() 메서드를 사용하면 CategoricalIndex에서 지정된 범주를 손쉽게 제거할 수 있습니다. 이 글에서는 기본 개념부터 실제 예제 코드와 실행 결과까지 단계별로 살펴보겠습니다.
1. 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
2. CategoricalIndex 생성
categories 매개변수를 사용해 범주형 데이터의 카테고리를 설정하고, ordered 매개변수를 통해 해당 범주를 순서가 있는(ordered) 범주로 지정합니다.
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
3. remove_categories()로 범주 제거
remove_categories() 메서드에 제거하려는 범주 목록을 매개변수로 전달합니다. 주의할 점은, 제거된 범주에 속해 있던 값들이 삭제되는 것이 아니라 NaN(결측값)으로 대체된다는 것입니다.
print("\n지정한 범주 제거 후 CategoricalIndex...\n", catIndex.remove_categories(["p", "q"]))전체 예제 코드
아래는 위 과정을 모두 포함한 완성된 코드입니다.
import pandas as pd
# categories 매개변수로 범주 설정
# ordered 매개변수로 순서가 있는 범주로 지정
catIndex = pd.CategoricalIndex(["p", "q", "r", "s", "p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"])
# CategoricalIndex 출력
print("CategoricalIndex...\n", catIndex)
# 범주 확인
print("\nCategoricalIndex의 범주 목록...\n", catIndex.categories)
# remove_categories()로 지정한 범주 제거
# 제거된 범주에 속한 값은 NaN으로 대체됨
print("\n지정한 범주 제거 후 CategoricalIndex...\n", catIndex.remove_categories(["p", "q"]))실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
CategoricalIndex... 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') CategoricalIndex after removing specified categories... CategoricalIndex([nan, nan, 'r', 's', nan, nan, 'r', 's'], categories=['r', 's'], ordered=True, dtype='category')
핵심 정리
remove_categories() 메서드는 원본 CategoricalIndex를 변경하지 않고 새로운 객체를 반환합니다. 제거된 범주('p', 'q')에 해당하던 값들은 NaN으로 바뀌며, 남은 범주 목록도 ['r', 's']로 갱신되는 것을 확인할 수 있습니다. 이처럼 불필요한 범주를 정리하면 데이터 분석 시 범주형 데이터를 더 깔끔하게 관리할 수 있습니다.