Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas IntervalArray - Check Intervals that share closed endpoints overlap or not
To check if intervals that share closed endpoints overlap or not, use the IntervalArray.overlaps() method in Pandas. Two intervals overlap if they share a common point, including closed endpoints.
Syntax
IntervalArray.overlaps(other)
Where other is an Interval object to check for overlaps against each interval in the array.
Creating an IntervalArray
First, let's create an IntervalArray with some sample intervals ?
import pandas as pd
# Create an IntervalArray with two intervals
intervals = pd.arrays.IntervalArray.from_tuples([(10, 20), (15, 35)])
print("IntervalArray...")
print(intervals)
print("\nInterval length...")
print(intervals.length)
IntervalArray... <IntervalArray> [(10, 20], (15, 35]] Length: 2, dtype: interval[int64, right] Interval length... Int64Index([10, 20], dtype='int64')
Checking for Overlaps with Closed Endpoints
Now let's check if these intervals overlap with a test interval that has left-closed endpoints ?
import pandas as pd
intervals = pd.arrays.IntervalArray.from_tuples([(10, 20), (15, 35)])
# Check overlaps with a left-closed interval
test_interval = pd.Interval(15, 28, closed='left')
print("Test interval:", test_interval)
result = intervals.overlaps(test_interval)
print("\nDoes interval share closed endpoints overlap?")
print(result)
Test interval: [15, 28) Does interval share closed endpoints overlap? [ True True]
Understanding the Results
The output shows [True True] because:
- First interval
(10, 20]overlaps with[15, 28)in the range [15, 20] - Second interval
(15, 35]overlaps with[15, 28)in the range [15, 28)
Different Closed Endpoint Examples
import pandas as pd
intervals = pd.arrays.IntervalArray.from_tuples([(5, 10), (10, 15), (20, 25)])
# Test with different closed endpoint configurations
test_right_closed = pd.Interval(10, 15, closed='right')
test_both_closed = pd.Interval(10, 15, closed='both')
print("Intervals:", intervals)
print("\nOverlaps with (10, 15]:", intervals.overlaps(test_right_closed))
print("Overlaps with [10, 15]:", intervals.overlaps(test_both_closed))
Intervals: <IntervalArray> [(5, 10], (10, 15], (20, 25]] Length: 3, dtype: interval[int64, right] Overlaps with (10, 15]: [False True False] Overlaps with [10, 15]: [ True True False]
Conclusion
The overlaps() method returns a boolean array indicating which intervals overlap with the test interval. The behavior depends on the closed endpoint configuration of both the IntervalArray and the test interval.
Advertisements
