Python Pandas – 检查两个共享封闭端点的Interval对象是否重叠
在这篇文章中,我们将介绍如何检查两个共享端点的区间是否重叠。为此,我们使用pandas的区间类和overlaps()方法进行所有与区间相关的操作。
语法:
Interval.overlaps()
参数:
- other : 区间对象。使用这个区间检查是否有重叠。
返回:bool .如果两个区间重叠,则返回真,否则返回假。
一步一步实现
Step 1:
导入所有需要的库。
import pandas
Step 2:
创建两个共享封闭端点的区间
pd.Interval(1,5, closed =both")
pd.Interval(5,10, closed="both")
Step 3:
使用overlaps()方法检查区间是否重叠。它返回一个bool。
IsOverlap = Interval1.overlaps(Interval2)
代码实现
例子1:创建,然后检查两个共享封闭端点的区间是否重叠。
# importing pandas library
import pandas as pd
# Creating two closed intervals that
# share the endpoint
Interval1 = pd.Interval(1, 5, closed='both')
Interval2 = pd.Interval(5, 10, closed='both')
# printing the intervals
print("Interval1 :", Interval1)
print("Interval2 :", Interval2)
# display the length of both Interval1
# and Interval2 objects
print("\nInterval1 object length = ", Interval1.length)
print("\nInterval2 object length = ", Interval2.length)
# Check whether both the intervals overlap
print("do the intervals overlap ? :", Interval1.overlaps(Interval2))
输出 :
例子2:创建并检查共享封闭端点的区间阵列是否与给定的区间[3,16]重叠。
# importing pandas library
import pandas as pd
Intervals = pd.arrays.IntervalArray.from_tuples(
[(1, 6), (6, 10), (10, 15), (20, 25)], closed="both")
# Display the IntervalArray
print("Intervals_array", Intervals)
# check if the given intervals overlap with [3,16]
print(Intervals.overlaps(pd.Interval(3, 16, closed='both')))
输出: