Pandas에서 조건이 False인 인덱스 값을 다른 값으로 교체하려면 Index.where() 메서드와 Index.isin() 메서드를 함께 사용하면 됩니다. where() 메서드는 조건이 True인 요소는 원래 값을 그대로 유지하고, False인 요소만 지정한 값으로 대체합니다. isin()은 특정 값 목록에 포함되어 있는지 여부를 판별하는 조건으로 활용됩니다.
1단계: 라이브러리 임포트
먼저 필요한 라이브러리를 가져옵니다.
import pandas as pd
2단계: Pandas 인덱스 생성
'Products'라는 이름을 가진 인덱스를 생성합니다.
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name='Products')
3단계: 인덱스 출력
생성된 Pandas 인덱스를 화면에 출력합니다.
print("Pandas Index...\n", index)
4단계: 조건이 False인 값 교체
where() 메서드에 조건과 대체할 값을 전달합니다. 이 예제에서는 'Decor'를 제외한 나머지 모든 요소가 'Miscellaneous'로 교체됩니다.
print("\nReplace index values where condition is False...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))
전체 예제 코드
지금까지의 내용을 하나로 정리한 전체 코드는 다음과 같습니다.
import pandas as pd
# Pandas 인덱스 생성
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name='Products')
# Pandas 인덱스 출력
print("Pandas Index...\n", index)
# 인덱스의 요소 개수 반환
print("\nNumber of elements in the index...\n", index.size)
# 데이터의 dtype 반환
print("\nThe dtype object...\n", index.dtype)
# 조건이 False인 값 교체
# 'Decor'를 제외한 모든 요소가 'Miscellaneous'로 교체됨
print("\nReplace index values where condition is False...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products') Number of elements in the index... 5 The dtype object... object Replace index values where condition is False... Index(['Miscellaneous', 'Miscellaneous', 'Decor', 'Miscellaneous', 'Miscellaneous'], dtype='object', name='Products')
핵심 정리
Index.where(조건, 대체값)은 조건이 True인 위치의 값은 유지하고, False인 위치의 값만 대체값으로 바꿉니다. 위 예제에서는 index.isin(['Decor'])을 조건으로 사용했기 때문에 'Decor' 하나만 원래 값으로 남고, 나머지 네 개 요소('Electronics', 'Accessories', 'Books', 'Toys')는 모두 'Miscellaneous'로 교체된 것을 확인할 수 있습니다. 이 방식은 특정 값만 남기고 나머지를 일괄 변경해야 할 때 매우 유용합니다.