Python Pandas – Check whether two Interval objects overlap
The panda’s Interval.overlaps() method is used to Check whether Interval objects are overlapping. Two intervals, including closed ends, overlap if they share the same point. Intervals that share only an open endpoint do not intersect.
Interval.overlaps() function:
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.
Example 1:
Pandas package is imported and two intervals are created using the pd.Interval() method. pd.Interval() method creates an object interval. pandas.Interval.overlaps() method is used to check whether the two intervals overlap and the result is returned.
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 ) |
Output:
first interval is :(5, 15] second interval is :(10, 25] do the intervals overlap ? : yes
Example 2:
when we don’t explicitly specify the closed parameter by default it’s ‘right’. the intervals have only one endpoint in common so they do not overlap.
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 ) |
Output:
first interval is :(0, 10] second interval is :(10, 20] do the intervals overlap ? : no
Here both intervals share closed endpoints so they overlap. The closed parameter is ‘both’ for both intervals.
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 ) |
Output:
first interval is :[0, 10] second interval is :[10, 20] do the intervals overlap ? : yes
Please Login to comment...