Để tìm chỉ số nơi một phần tử đơn lẻ nên được chèn vào Index để giữ thứ tự, sử dụng phương thức index.searchsorted() với một giá trị scalar.
Các bước thực hiện
- Import thư viện:
import pandas as pd - Tạo Index đã sắp xếp:
index = pd.Index([10, 20, 30, 40, 50]) - Gọi
index.searchsorted(45).
Ví dụ hoàn chỉnh
import pandas as pd
index = pd.Index([10, 20, 30, 40, 50])
print("Pandas Index...\n", index)
print("\nNumber of elements in the index...\n", index.size)
# Tìm vị trí chèn cho giá trị đơn lẻ
print("\nThe exact positions where the element should be placed?...\n", index.searchsorted(45))
Kết quả
Pandas Index...
Int64Index([10, 20, 30, 40, 50], dtype='int64')
Number of elements in the index...
5
The exact positions where the element should be placed?...
4
Giải thích: Giá trị 45 nên chèn tại vị trí 4 (giữa 40 và 50). Trả về số nguyên đơn lẻ thay vì mảng.