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

Python Pandas - ตรวจสอบว่าองค์ประกอบอยู่ใน Interval หรือไม่

เพื่อตรวจสอบว่าองค์ประกอบอยู่ใน Interval หรือไม่ ให้ใช้ operator in

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

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

import pandas as pd

2. สร้าง Time Interval

โดยค่าเริ่มต้น closed='right' คือ (0, 10]

interval = pd.Interval(left=0, right=10)

3. แสดง Interval

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

4. ตรวจสอบการมีอยู่ขององค์ประกอบ

print("\nThe specific element exists in the Interval? = \n", 6 in interval)

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

import pandas as pd

# สร้าง time interval
interval = pd.Interval(left=0, right=10)

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

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

# ตรวจสอบองค์ประกอบ
print("\nThe specific element exists in the Interval? = \n", 6 in interval)

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

Interval... 
(0, 10]
Interval length... 
10
The specific element exists in the Interval? = 
True

คำอธิบาย: Interval (0, 10] ไม่รวม 0 แต่รวม 10 เลข 6 อยู่ในช่วงนี้ จึงคืนค่า True สามารถใช้ in ตรวจสอบได้โดยตรง