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

Python Pandas - คำนวณขอบเขตขวา (Right Slice Bound) ที่ตรงกับป้ายกำกับที่กำหนด

เพื่อคำนวณขอบเขตขวา (right slice bound) ที่ตรงกับป้ายกำกับที่กำหนด ให้ใช้เมธอด index.get_slice_bound() ตั้งค่าพารามิเตอร์ side เป็น right

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

import pandas as pd

สร้าง Pandas Index:

index = pd.Index([10, 20, 30, 40, 50, 60, 70])

แสดง Pandas Index:

print("Pandas Index...\n", index)

ดึงขอบเขตขวา (right slice bound) คืนค่าขอบเขตขวาของป้ายกำกับที่กำหนด หากพารามิเตอร์ "side" ตั้งเป็น "right":

print("\nGet the right slice bound...\n", index.get_slice_bound(30, side='right', kind='getitem'))

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

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)

# Get the right slice bound
# Returns the right slice bound of given label if "side" parameter is set to "right"
print("\nGet the right slice bound...\n", index.get_slice_bound(30, side='right', kind='getitem'))

เอาต์พุต

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

Pandas Index... Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')
Number of elements in the index... 7
Get the right slice bound... 3