Python Pandas - Check whether two Interval objects that share an open endpoint overlap

PythonServer Side ProgrammingProgramming

To check whether two Interval objects that share an open endpoint overlap, use the overlaps() method.

At first, import the required libraries −

import pandas as pd

Two intervals overlap if they share a common point, including closed endpoints. Intervals that only have an open endpoint in common do not overlap.

Create two Interval objects. Interval1 is closed from both sides. Interval2 is open from both sides −

interval1 = pd.Interval(10, 30, closed='both')
interval2 = pd.Interval(30, 50, closed='neither')

Display the intervals −

print("Interval1...
",interval1)
print("Interval2...
",interval2)

Check whether both the interval objects overlap −

print("
Do both the interval objects overlap?
",interval1.overlaps(interval2))

Example

Following is the code −

import pandas as pd

# Two intervals overlap if they share a common point, including closed endpoints
# Intervals that only have an open endpoint in common do not overlap
# Create two Interval objects
# Interval1 is closed from both sides
# Interval2 is open from both sides
interval1 = pd.Interval(10, 30, closed='both')
interval2 = pd.Interval(30, 50, closed='neither')

# display the intervals
print("Interval1...
",interval1)
print("Interval2...
",interval2)

# display the length of both Interval1 and Interval2 objects
print("
Interval1 object length = ",interval1.length)
print("
Interval2 object length = ",interval2.length)

# check whether both the interval objects overlap
print("
Do both the interval objects overlap?
",interval1.overlaps(interval2))

Output

This will produce the following code −

Interval1...
[10, 30]
Interval2...
(30, 50)
Interval1 object length = 20
Interval2 object length = 20
Do both the interval objects overlap?
False
raja
Updated on 12-Oct-2021 11:51:04

Advertisements