Để lấy vị trí nguyên cho một nhãn và tìm chỉ số trước đó (previous) nếu không có khớp chính xác, sử dụng phương thức index.get_loc() với tham số method='ffill' (forward fill).
Các bước thực hiện
- Import thư viện:
import pandas as pd - Tạo Index:
index = pd.Index([10, 20, 30, 40, 50, 60, 70]) - Gọi
index.get_loc(45, method="ffill")để tìm chỉ số lớn nhất nhỏ hơn hoặc bằng 45.
Ví dụ hoàn chỉnh
import pandas as pd
# Tạo Pandas Index
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
# Hiển thị Index
print("Pandas Index...\n", index)
# Lấy vị trí nguyên cho nhãn có sẵn
print("\nDisplay integer location from given index...\n", index.get_loc(20)) # 1
print("\nDisplay integer location from given index...\n", index.get_loc(50)) # 4
# Lấy vị trí chỉ số trước đó nếu không khớp chính xác (ffill)
print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill")) # 3 (nhãn 40)
Kết quả
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
Giải thích: Với method='ffill', giá trị 45 không có trong index, nên trả về vị trí của nhãn trước đó gần nhất là 40 (chỉ số 3).