Pandas에서 CategoricalIndex.map() 메서드를 사용하면 사전(dict)과 같은 입력 대응 관계를 기반으로 값을 손쉽게 매핑할 수 있습니다. 이 메서드는 각 범주를 지정한 딕셔너리의 키와 비교하여, 해당하는 값(value)으로 변환해 줍니다.
1. 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
2. 순서가 있는 CategoricalIndex 생성
categories 매개변수를 사용해 범주를 설정하고, ordered 매개변수를 True로 지정하면 해당 범주형 데이터를 순서가 있는(ordered) 범주로 취급합니다.
catIndex = pd.CategoricalIndex(["P", "Q", "R", "S", "P", "Q", "R", "S"], ordered=True, categories=["P", "Q", "R", "S"])
3. CategoricalIndex 출력하기
생성된 CategoricalIndex를 화면에 표시합니다.
print("CategoricalIndex...\n", catIndex)4. 사전을 이용한 범주 매핑
이제 딕셔너리 형태의 매핑 규칙을 map() 메서드에 전달하여 범주를 새로운 값으로 변환합니다.
print("\nCategoricalIndex after mapping...\n", catIndex.map({'P': 5, 'Q': 10, 'R': 15, 'S': 20}))전체 예제 코드
지금까지의 과정을 하나로 정리한 전체 코드는 다음과 같습니다.
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)
# 범주(categories) 확인
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# 사전을 이용해 범주 매핑
print("\nCategoricalIndex after mapping...\n", catIndex.map({'P': 5, 'Q': 10, 'R': 15, 'S': 20}))실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
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 mapping... CategoricalIndex([5, 10, 15, 20, 5, 10, 15, 20], categories=[5, 10, 15, 20], ordered=True, dtype='category')
정리
CategoricalIndex.map()은 딕셔너리를 인자로 받아 각 범주를 새로운 값으로 변환합니다. 위 예제에서 볼 수 있듯이, 문자열 범주('P', 'Q', 'R', 'S')가 숫자 값(5, 10, 15, 20)으로 매핑되었으며, 원래의 순서(ordered=True) 속성도 그대로 유지됩니다. 이 방법은 범주형 데이터를 점수, 등급, 코드 등 다른 값 체계로 변환할 때 매우 유용하게 활용됩니다.