Check elementwise if an Interval overlaps the values in the IntervalArray in Python Pandas

PythonServer Side ProgrammingProgramming

To check elementwise if an Interval overlaps the values in the IntervalArray, use the overlaps() method in Pandas.

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 an IntervalArray −

intervals = pd.arrays.IntervalArray.from_tuples([(10, 20), (15, 35)])

Display the IntervalArray −

print("IntervalArray...
",intervals)

Check elementwise if an Interval overlaps the values in the IntervalArray −

print("
Does interval overlaps values in the IntervalArray...
",intervals.overlaps(pd.Interval(12, 30)))

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 an IntervalArray
intervals = pd.arrays.IntervalArray.from_tuples([(10, 20), (15, 35)])

# Display the IntervalArray
print("IntervalArray...
",intervals)

# Display the interval length
print("
Interval length...
",intervals.length)

# Check elementwise if an Interval overlaps the values in the IntervalArray
print("
Does interval overlaps values in the IntervalArray...
",intervals.overlaps(pd.Interval(12, 30)))

Output

This will produce the following output −

IntervalArray...
<IntervalArray>
[(10, 20], (15, 35]]
Length: 2, dtype: interval[int64, right]

Interval length...
Int64Index([10, 20], dtype='int64')

Does interval overlaps values in the IntervalArray...
[ True True]
raja
Updated on 19-Oct-2021 06:28:00

Advertisements