Để tính indexer và tìm chỉ số tiếp theo (backward fill / bfill) nếu không khớp chính xác, sử dụng phương thức index.get_indexer() với tham số method='bfill'.
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_indexer([30, 25, 58, 50, 55], method="bfill").
Ví dụ hoàn chỉnh
import pandas as pd
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
print("Pandas Index...\n", index)
print("\nNumber of elements in the index...\n", index.size)
# Tính indexer với method='bfill' (tìm giá trị tiếp theo lớn hơn hoặc bằng)
print("\nGet the indexes...\n", index.get_indexer([30, 25, 58, 50, 55], method="bfill"))
Kết quả
Pandas Index...
Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')
Number of elements in the index...
7
Get the indexes...
[2 2 5 4 5]
Giải thích:
- 30 → chỉ số 2 (khớp chính xác)
- 25 → giá trị tiếp theo ≥ 25 là 30 → chỉ số 2
- 58 → giá trị tiếp theo ≥ 58 là 60 → chỉ số 5
- 50 → chỉ số 4
- 55 → giá trị tiếp theo ≥ 55 là 60 → chỉ số 5