Python Pandas에서 요청한 레이블(label)에 해당하는 정수 위치(integer location)를 구하고, 정확히 일치하는 값이 없을 경우 이전 인덱스 값을 찾으려면 Index.get_loc() 메서드를 사용하면 됩니다. 이때 method 매개변수에 "ffill"(forward fill)을 지정하면, 정확한 일치 항목이 없어도 바로 앞에 있는 인덱스의 위치를 반환합니다.
기본 사용법
먼저 필요한 라이브러리를 임포트합니다.
import pandas as pd
Pandas 인덱스를 생성합니다.
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
생성된 Pandas 인덱스를 화면에 출력해 확인합니다.
print("Pandas Index...\n", index)
get_loc()의 method 매개변수에 "ffill" 값을 설정하면, 정확히 일치하는 레이블이 없을 때 이전 인덱스의 위치를 반환받을 수 있습니다. 아래 예시에서는 인덱스에 존재하지 않는 값 45를 검색합니다.
print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))
45는 인덱스에 없지만, 바로 앞에 있는 40의 위치인 3이 결과로 반환됩니다.
예제 코드
전체 코드는 다음과 같습니다.
import pandas as pd
# Pandas 인덱스 생성
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
# Pandas 인덱스 출력
print("Pandas Index...\n", index)
# 인덱스에 포함된 요소 개수 확인
print("\nNumber of elements in the index...\n", index.size)
# 주어진 레이블로부터 정수 위치 조회
print("\nDisplay integer location from given index...\n", index.get_loc(20))
print("\nDisplay integer location from given index...\n", index.get_loc(50))
# 정확히 일치하지 않을 경우 이전 인덱스의 위치 반환
# get_loc()의 method 매개변수에 "ffill" 값 설정
print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Pandas Index... Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64') Number of elements in the index... 7 Display integer location from given index... 1 Display integer location from given index... 4 Get the location of the previous index if no exact match... 3
핵심 정리
- get_loc() : 인덱스에서 특정 레이블의 정수 위치(0부터 시작)를 반환합니다.
- method="ffill" : 정확한 일치가 없을 때 이전(forward) 인덱스 값의 위치를 반환합니다.
- method="bfill" : 반대로 다음(backward) 인덱스 값의 위치를 반환할 때 사용합니다.