Python Pandas - Check elementwise if an Interval overlaps the values in the IntervalArray created from an array of splits

PythonPandasServer Side ProgrammingProgramming

To check elementwise if an Interval overlaps the values in the IntervalArray created from an array of splits, use the array.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. Construct a new IntervalArray from an array-like of splits −

array = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3, 4, 5])

Display the intervals −

print("Our IntervalArray...\n",array)

Check for overlap −

print("\nDoes the Interval overlaps the values in the IntervalArray", array.overlaps(pd.Interval(2.5, 3.2)))

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.
# Construct a new IntervalArray from an array-like of splits
array = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3, 4, 5])

# Display the IntervalArray
print("Our IntervalArray...\n",array)

# check for overlap
print("\nDoes the Interval overlaps the values in the IntervalArray", array.overlaps(pd.Interval(2.5, 3.2)))

Output

This will produce the following code −

Our IntervalArray...
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]]
Length: 5, dtype: interval[int64, right]

Does the Interval overlaps the values in the IntervalArray [False False True True False]
raja
Updated on 13-Oct-2021 11:03:52

Advertisements