Computer >> Computer tutorials >  >> Programming >> Python

Python Pandas - Check elementwise if the Intervals in the IntervalIndex contain the value


To check elementwise if the Intervals in the IntervalIndex contain the value, use the IntervalIndex. contains() method in Pandas.

At first, import the required libraries −

import pandas as pd

Create IntervalIndex −

interval = pd.IntervalIndex.from_tuples([(10, 20), (15, 25)])

Display the interval −

print("IntervalIndex...\n",interval)

Check if the interval contains a specific value −

print("\nDoes the interval contain a specific value?\n",interval.contains(13))

Example

Following is the code −

import pandas as pd

# Create IntervalIndex
interval = pd.IntervalIndex.from_tuples([(10, 20), (15, 25)])

# Display the interval
print("IntervalIndex...\n",interval)

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

# Check if the interval contains a specific value
print("\nDoes the interval contain a specific value?\n",interval.contains(13))

Output

This will produce the following output −

IntervalIndex...
IntervalIndex([(10, 20], (15, 25]], dtype='interval[int64, right]')

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

Does the interval contain a specific value?
[ True False]