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


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...\n",intervals)

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

print("\nDoes interval overlaps values in the IntervalArray...\n",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...\n",intervals)

# Display the interval length
print("\nInterval length...\n",intervals.length)

# Check elementwise if an Interval overlaps the values in the IntervalArray
print("\nDoes interval overlaps values in the IntervalArray...\n",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]

Updated on: 19-Oct-2021

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements