Python Pandas IntervalIndex - Get the locations of all the relevant interval if a label is in several intervals

PythonServer Side ProgrammingProgramming

To get the locations of all the relevant interval if a label is in several intervals, use the get_loc() method in Pandas.

At first, import the required libraries −

import pandas as pd

Create two Interval objects. Closed intervals set using the "closed" parameter with value "both"

interval1 = pd.Interval(50, 75)
interval2 = pd.Interval(75, 90)
interval3 = pd.Interval(50, 90)

Create IntervalIndex from the three intervals −

index = pd.IntervalIndex([interval1, interval2, interval3])

Get the locations of all the relevant interval if a label is in several intervals −

print("\nGet the locations of all the relevant interval...\n",index.get_loc(65))

Example

Following is the code −

import pandas as pd

# Create two Interval objects
# Closed intervals set using the "closed" parameter with value "both"
interval1 = pd.Interval(50, 75)
interval2 = pd.Interval(75, 90)
interval3 = pd.Interval(50, 90)

# display the intervals
print("Interval1...\n",interval1)
print("Interval2...\n",interval2)
print("Interval3...\n",interval3)

# Create IntervalIndex from the three intervals
index = pd.IntervalIndex([interval1, interval2, interval3])

# Get the locations of all the relevant interval if a label is in several intervals
print("\nGet the locations of all the relevant interval...\n",index.get_loc(65))

Output

This will produce the following output −

Interval1...
(50, 75]
Interval2...
(75, 90]
Interval3...
(50, 90]

Get the locations of all the relevant interval...
[ True False True]
raja
Updated on 18-Oct-2021 07:59:43

Advertisements