เพื่อคำนวณ Indexer และหาค่า Index ใกล้เคียงที่สุดหากไม่มีค่าตรงกันพอดี ให้ใช้เมธอด index.get_indexer() พร้อมตั้งค่าพารามิเตอร์ method เป็น nearest
เริ่มต้นด้วยการนำเข้าไลบรารีที่จำเป็น:
import pandas as pd
สร้าง Pandas Index:
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
แสดง Pandas Index:
print("Pandas Index...\n", index)
คำนวณ Indexer และ Mask ด้วย "get_indexer" หาค่า Index ใกล้เคียงที่สุดหากไม่มีค่าตรงกันพอดี โดยใช้พารามิเตอร์ "method" ตั้งค่าเป็น "nearest":
print("\nGet the indexes...\n", index.get_indexer([30, 25, 58, 50, 69], method="nearest"))
ตัวอย่างโค้ดเต็ม
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)
# Compute indexer and mask using the "get_indexer"
# Find the nearest index value if no exact match using the "method" parameter.
# The value is set "nearest"
print("\nGet the indexes...\n", index.get_indexer([30, 25, 58, 50, 69], method="nearest"))
เอาต์พุต
จะได้ผลลัพธ์ดังนี้:
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 6]