📌  相关文章
📜  Python Pandas – 检查共享封闭端点的两个 Interval 对象是否重叠

📅  最后修改于: 2022-05-13 01:54:26.337000             🧑  作者: Mango

Python Pandas – 检查共享封闭端点的两个 Interval 对象是否重叠

在本文中,我们将介绍如何检查具有共享端点的两个区间是否重叠。为此,我们使用 pandas 的 Interval 类和所有与间隔相关的操作的重叠()方法。

逐步实施

第1步:

导入所有需要的库。

import pandas

第2步:

创建共享封闭端点的两个区间

pd.Interval(1,5, closed =both")
pd.Interval(5,10, closed="both")

第 3 步:

使用overlaps() 方法检查间隔是否重叠。它返回一个布尔值。

IsOverlap = Interval1.overlaps(Interval2)

代码实现

示例 1:创建并检查共享闭合端点的两个区间是否重叠。

Python3
# 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))


Python3
# 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')))


输出

示例 2:创建并检查共享闭合端点的区间数组是否与给定区间重叠 [3,16]。

Python3

# 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')))

输出: