Python Pandas - Check if the Intervals in the IntervalArray is empty

PythonServer Side ProgrammingProgramming

To check if the Intervals in the IntervalArray is empty, use the array.is_empty property in Pandas.

At first, import the required libraries −

import pandas as pd

Create two Interval objects. Open interval set using the "closed" parameter with value "neither" −

interval1 = pd.Interval(0, 0, closed='neither')
interval2 = pd.Interval(20, 50, closed='neither')

Display the intervals −

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

Construct a new IntervalArray from Interval objects −

array = pd.arrays.IntervalArray([interval1,interval2])

Check if the Intervals in the IntervalArray is empty −

print("\nCheck if IntervalArray is empty?\n",array.is_empty)

Example

Following is the code −

import pandas as pd

# Create two Interval objects
# Open interval set using the "closed" parameter with value "neither"
interval1 = pd.Interval(0, 0, closed='neither')
interval2 = pd.Interval(20, 50, closed='neither')

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

# display the interval length
print("\nInterval1 length...\n",interval1.length)
print("\nInterval2 length...\n",interval2.length)

# Construct a new IntervalArray from Interval objects
array = pd.arrays.IntervalArray([interval1,interval2])

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

# Getting the length of IntervalArray
# Returns an Index with entries denoting the length of each Interval in the IntervalArray
print("\nOur IntervalArray length...\n",array.length)

# Check if the Intervals in the IntervalArray is empty
print("\nCheck if IntervalArray is empty?\n",array.is_empty)

Output

This will produce the following code −

Interval1...
(0, 0)
Interval2...
(20, 50)

Interval1 length...
0

Interval2 length...
30

Our IntervalArray...
<IntervalArray>
[(0, 0), (20, 50)]
Length: 2, dtype: interval[int64, neither]

Our IntervalArray length...
Int64Index([0, 30], dtype='int64')

Check if IntervalArray is empty?
[ True False]
raja
Updated on 12-Oct-2021 12:36:29

Advertisements