Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Pandas - 요청된 레이블의 정수 위치를 가져오고 정확히 일치하지 않으면 이전 인덱스 값을 찾습니다.

<시간/>

요청한 레이블에 대한 정수 위치를 가져오고 정확히 일치하지 않는 경우 이전 색인 값을 찾으려면 index.get_loc()을 사용하세요. . 매개변수 메서드 설정 채우기 값으로 .

먼저 필요한 라이브러리를 가져옵니다 -

import pandas as pd

팬더 인덱스 생성 -

index = pd.Index([10, 20, 30, 40, 50, 60, 70])

판다 인덱스 표시 -

print("Pandas Index...\n",index)

정확히 일치하지 않는 경우 이전 인덱스의 위치를 ​​가져옵니다. 값은 get_loc() -

의 "method" 매개변수를 사용하여 "ffill"로 설정됩니다.
print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))

예시

다음은 코드입니다 -

import pandas as pd

# Creating Pandas index
index = pd.Index([10, 20, 30, 40, 50, 60, 70])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# get integer location from the given index
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 the location of the previous index if no exact match
# The value is set "ffill" using the "method" parameter of the get_loc()
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