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

Python Pandas - สร้างช่วงเวลาครึ่งเปิดและตรวจสอบจุดปลาย

เพื่อสร้าง half-open time interval (ช่วงเวลาครึ่งเปิด) ให้ใช้ pandas.Interval() ตั้งค่า closed='left' เพื่อตรวจสอบการมีอยู่ของจุดปลาย ใช้ operator in

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้าง Half-Open Interval (ปิดทางซ้าย)

closed='left' หมายถึง [0, 5) ซึ่งอธิบายได้โดย 0 ≤ x < 5

interval = pd.Interval(left=0, right=20, closed='left')

3. แสดง Interval

print("Interval...\n", interval)

4. ตรวจสอบการมีอยู่ของจุดปลาย

print("\nThe left-most element exists in the Interval? = \n", 0 in interval)
print("\nThe right-most element exists in the Interval? = \n", 20 in interval)

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# สร้าง Half-Open interval (ปิดทางซ้าย)
interval = pd.Interval(left=0, right=20, closed='left')

# แสดง interval
print("Interval...\n", interval)

# แสดงความยาว
print("\nInterval length...\n", interval.length)

# ตรวจสอบจุดปลาย
print("\nThe left-most element exists in the Interval? = \n", 0 in interval)
print("\nThe right-most element exists in the Interval? = \n", 20 in interval)

ผลลัพธ์ที่คาดหวัง

Interval... 
[0, 20)
Interval length... 
20

The left-most element exists in the Interval? = 
True
The right-most element exists in the Interval? = 
False

คำอธิบาย: ช่วง [0, 20) รวม 0 (ขอบซ้าย) แต่ไม่รวม 20 (ขอบขวา) เรียกว่า half-open interval