Pandas에서 MultiIndex 객체에 대해 요청한 레이블(label) 또는 레벨(level)에 해당하는 위치(location)와 슬라이스 인덱스(sliced index)를 확인하려면 get_loc_level() 메서드를 사용하면 됩니다. 이 메서드는 지정한 레이블이 어느 위치에 있는지, 그리고 해당 레이블과 연관된 하위 인덱스가 무엇인지 튜플 형태로 반환해 줍니다.
필요한 라이브러리 임포트
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
MultiIndex 생성하기
MultiIndex는 pandas 객체에서 사용할 수 있는 다중 레벨(hierarchical) 인덱스 객체입니다. 여기서는 두 개의 배열을 결합하여 'One'과 'Two'라는 이름을 가진 MultiIndex를 만들어 보겠습니다.
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')], names=['One', 'Two'])생성된 MultiIndex를 화면에 출력합니다.
print("The MultiIndex...\n", multiIndex)그다음 get_loc_level() 메서드를 호출하여 위치와 슬라이스 인덱스를 가져옵니다.
print("\nGet the location and sliced index...\n", multiIndex.get_loc_level('r'))전체 예제 코드
아래는 위 과정을 하나로 정리한 전체 코드입니다.
import pandas as pd
# MultiIndex는 pandas 객체를 위한 다중 레벨(계층적) 인덱스 객체입니다.
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')], names=['One', 'Two'])
# MultiIndex 출력
print("The MultiIndex...\n", multiIndex)
# MultiIndex의 레벨(levels) 확인
print("\nThe levels in MultiIndex...\n", multiIndex.levels)
# 위치와 슬라이스 인덱스 가져오기
print("\nGet the location and sliced index...\n", multiIndex.get_loc_level('r'))실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
The MultiIndex...
MultiIndex([('p', 's'),
('q', 't'),
('r', 'r'),
('r', 'v'),
('s', 'w'),
('s', 'x')],
names=['One', 'Two'])
The levels in MultiIndex...
[['p', 'q', 'r', 's'], ['r', 's', 't', 'v', 'w', 'x']]
Get the location and sliced index...
(slice(2, 4, None), Index(['r', 'v'], dtype='object', name='Two'))결과 해석
출력 결과를 살펴보면, 첫 번째 레벨('One')에서 레이블 'r'은 인덱스 2번부터 4번 직전까지, 즉 슬라이스 slice(2, 4, None) 범위에 위치하고 있습니다. 또한 해당 위치에 대응하는 두 번째 레벨('Two')의 값은 'r'과 'v'임을 알 수 있습니다. 이처럼 get_loc_level() 메서드는 계층적 인덱스에서 특정 레이블의 정확한 위치와 관련 하위 인덱스를 한 번에 파악할 수 있게 해주는 유용한 도구입니다.