Pandas에서 람다(lambda) 함수를 사용해 카테고리의 이름을 변경하려면 CategoricalIndex의 rename_categories() 메서드를 활용하면 됩니다.
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
CategoricalIndex는 제한적이고 대개 고정된 개수의 가능한 값만 가질 수 있습니다. categories 매개변수를 사용해 범주형 데이터의 카테고리를 설정하고, ordered 매개변수를 사용해 해당 범주형을 순서가 있는(ordered) 것으로 지정합니다.
catIndex = pd.CategoricalIndex(["P", "Q", "R", "S", "P", "Q", "R", "S"], ordered=True, categories=["P", "Q", "R", "S"])
생성된 CategoricalIndex를 출력해 확인해 보겠습니다.
print("CategoricalIndex...\n", catIndex)이제 rename_categories() 메서드로 카테고리 이름을 변경합니다. 람다 함수를 활용해 모든 카테고리를 소문자로 변환하는 새 카테고리를 설정합니다.
print("\nCategoricalIndex after renaming categories...\n", catIndex.rename_categories(lambda a: a.lower()))전체 예제 코드
다음은 위 과정을 정리한 전체 코드입니다.
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"])
# CategoricalIndex 출력
print("CategoricalIndex...\n", catIndex)
# 카테고리 목록 확인
print("\nDisplaying Categories from CategoricalIndex...\n", catIndex.categories)
# rename_categories()로 카테고리 이름 변경
# 람다 함수를 사용해 모든 카테고리를 소문자로 변환
print("\nCategoricalIndex after renaming categories...\n", catIndex.rename_categories(lambda a: a.lower()))실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
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 renaming categories... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')
출력 결과에서 볼 수 있듯이, 람다 함수에 의해 기존의 대문자 카테고리('P', 'Q', 'R', 'S')가 소문자('p', 'q', 'r', 's')로 성공적으로 변환되었으며, 순서 정보(ordered=True)는 그대로 유지됩니다. 이처럼 rename_categories() 메서드는 리스트뿐만 아니라 람다 함수도 인자로 받을 수 있어, 카테고리 이름을 유연하게 일괄 변환할 때 매우 유용합니다.