Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas - Nhận vị trí số nguyên cho nhãn được yêu cầu và tìm giá trị chỉ mục trước đó nếu không có khớp chính xác

Để nhận vị trí số nguyên cho nhãn được yêu cầu và tìm giá trị chỉ mục trước đó nếu không có kết quả khớp chính xác, hãy sử dụng index.get_loc () . Đặt tham số phương pháp đến giá trị ffill .

Đầu tiên, hãy nhập các thư viện được yêu cầu -

import pandas as pd

Tạo chỉ mục Pandas -

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

Hiển thị chỉ mục Gấu trúc -

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

Lấy vị trí của chỉ mục trước đó nếu không có kết quả khớp chính xác. Giá trị được đặt "ffill" bằng cách sử dụng tham số "method" của get_loc () -

print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))

Ví dụ

Sau đây là mã -

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"))

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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