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

Python Pandas - Check if the Pandas Index holds Interval objects


To check if the Pandas Index holds Interval objects, use the index.is_interval() method in Pandas.

At first, import the required libraries -

import pandas as pd

Create Interval objects −

interval1 = pd.Interval(10, 30)
interval2 = pd.Interval(30, 50)

Display the intervals −

print("Interval1...\n",interval1)
print("Interval2...\n",interval2)

Creating Pandas index with Interval object1 and 2 −

index = pd.Index([interval1,interval2])

Check whether index values has only interval objects −

print("\nDoes Index consists of Interval objects?\n", index.is_interval())

Example

Following is the code −

import pandas as pd

# create Interval objects
interval1 = pd.Interval(10, 30)
interval2 = pd.Interval(30, 50)

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

# Creating Pandas index with Interval object1 and 2
index = pd.Index([interval1,interval2])

# Display the Pandas index
print("\nPandas Index...\n",index)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# check whether index values has only ints
print("\nDoes Index consists of Interval objects?\n", index.is_interval())

Output

This will produce the following output −

Interval1...
(10, 30]
Interval2...
(30, 50]

Pandas Index...
IntervalIndex([(10, 30], (30, 50]], dtype='interval[int64, right]')

The dtype object...
interval[int64, right]

Does Index consists of Interval objects?
True