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

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

เพื่อคำนวณ Indexer และหาค่า Index ก่อนหน้า (previous) หากไม่มีค่าตรงกันพอดี ให้ใช้เมธอด index.get_indexer() พร้อมตั้งค่าพารามิเตอร์ method เป็น ffill (forward 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" ตั้งค่าเป็น "ffill":

print("\nGet the indexes...\n", index.get_indexer([30, 20, 75, 80, 50, 59], method="ffill"))

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

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 previous index value if no exact match using the "method" parameter.
# The value is set "ffill"
print("\nGet the indexes...\n", index.get_indexer([30, 20, 75, 80, 50, 59], method="ffill"))

เอาต์พุต

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

Pandas Index... Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')
Number of elements in the index... 7
Get the indexes... [2 1 6 6 4 4]