Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - คำนวณ Indexer และหาค่า Index ถัดไปหากไม่มีค่าตรงกัน

เพื่อคำนวณ Indexer และหาค่า Index ถัดไป (next) หากไม่มีค่าตรงกันพอดี ให้ใช้เมธอด index.get_indexer() พร้อมตั้งค่าพารามิเตอร์ method เป็น bfill (backward fill)

เริ่มต้นด้วยการนำเข้าไลบรารีที่จำเป็น:

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" ตั้งค่าเป็น "bfill":

print("\nGet the indexes...\n", index.get_indexer([30, 25, 58, 50, 55], method="bfill"))

ตัวอย่างโค้ดเต็ม

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 next index value if no exact match using the "method" parameter.
# The value is set "bfill"
print("\nGet the indexes...\n", index.get_indexer([30, 25, 58, 50, 55], method="bfill"))

เอาต์พุต

จะได้ผลลัพธ์ดังนี้:

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]