Python Pandas – 检查两个 Interval 对象是否重叠
panda 的 Interval.overlaps() 方法用于检查 Interval 对象是否重叠。如果两个区间(包括闭合端)共享同一点,则它们会重叠。仅共享一个开放端点的区间不相交。
Interval.overlaps()函数:
Syntax: Interval.overlaps()
parameters:
other : interval object. Check for an overlap using this interval.
Returns : bool . returns true if two intervals overlap. else it returns false.
示例 1:
导入 Pandas 包并使用 pd.Interval() 方法创建两个间隔。 pd.Interval() 方法创建一个对象间隔。 pandas.Interval.overlaps() 方法用于检查两个区间是否重叠并返回结果。
Python3
# import packages
import pandas as pd
# creating 1st interval
interval1 = pd.Interval(5, 15)
print('first interval is :' + str(interval1))
# creating 2nd interval
interval2 = pd.Interval(10, 25)
# checking whether the intervals overlap
result = interval1.overlaps(interval2)
print('second interval is :'+str(interval2))
str = 'yes' if result else 'no'
print('do the intervals overlap ? : '+str)
Python3
# import packages
import pandas as pd
# creating 1st interval
interval1 = pd.Interval(0, 10)
print('first interval is :' + str(interval1))
# creating 2nd interval
interval2 = pd.Interval(10, 20)
# checking whether the intervals overlap
result = interval1.overlaps(interval2)
print('second interval is :'+str(interval2))
str = 'yes' if result else 'no'
print('do the intervals overlap ? : '+str)
Python3
# import packages
import pandas as pd
# creating 1st interval
interval1 = pd.Interval(0, 10, closed='both')
print('first interval is :' + str(interval1))
# creating 2nd interval
interval2 = pd.Interval(10, 20, closed='both')
# checking whether the intervals overlap
result = interval1.overlaps(interval2)
print('second interval is :'+str(interval2))
str = 'yes' if result else 'no'
print('do the intervals overlap ? : '+str)
输出:
first interval is :(5, 15]
second interval is :(10, 25]
do the intervals overlap ? : yes
示例 2:
当我们没有明确指定默认关闭参数时,它是“正确的”。间隔只有一个共同端点,因此它们不会重叠。
Python3
# import packages
import pandas as pd
# creating 1st interval
interval1 = pd.Interval(0, 10)
print('first interval is :' + str(interval1))
# creating 2nd interval
interval2 = pd.Interval(10, 20)
# checking whether the intervals overlap
result = interval1.overlaps(interval2)
print('second interval is :'+str(interval2))
str = 'yes' if result else 'no'
print('do the intervals overlap ? : '+str)
输出:
first interval is :(0, 10]
second interval is :(10, 20]
do the intervals overlap ? : no
在这里,两个区间共享封闭端点,因此它们重叠。两个区间的封闭参数都是“两者”。
Python3
# import packages
import pandas as pd
# creating 1st interval
interval1 = pd.Interval(0, 10, closed='both')
print('first interval is :' + str(interval1))
# creating 2nd interval
interval2 = pd.Interval(10, 20, closed='both')
# checking whether the intervals overlap
result = interval1.overlaps(interval2)
print('second interval is :'+str(interval2))
str = 'yes' if result else 'no'
print('do the intervals overlap ? : '+str)
输出:
first interval is :[0, 10]
second interval is :[10, 20]
do the intervals overlap ? : yes