Python Pandas - Check whether the intervals in IntervalArray are closed on the left-side, right-side, both or neither


To check whether the intervals in IntervalArray are closed on the left-side, right-side, both or neither, use the array.closed property.

At first, import the required libraries −

import pandas as pd

Create two Interval objects. Closed intervals set using the "closed" parameter with value "both". A closed interval (in mathematics denoted by square brackets) contains its endpoints, i.e. the closed interval [0, 5] is characterized by the conditions 0 <= x <= 5 −

interval1 = pd.Interval(10, 25, closed='both')
interval2 = pd.Interval(15, 70, closed='both')

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 whether the intervals in the Interval Array is closed on the left-side, right-side, both or neither −

print("\nChecking whether the intervals is closed...\n",array.closed)

Example

Following is the code −

import pandas as pd

# Create two Interval objects
# Closed intervals set using the "closed" parameter with value "both"
# A closed interval (in mathematics denoted by square brackets) contains its endpoints,
# i.e. the closed interval [0, 5] is characterized by the conditions 0 <= x <= 5
interval1 = pd.Interval(10, 25, closed='both')
interval2 = pd.Interval(15, 70, closed='both')

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

# 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 whether the intervals in the Interval Array is closed on the left-side, right-side,
# both or neither
print("\nChecking whether the intervals is closed...\n",array.closed)

Output

This will produce the following code −

Interval1...
[10, 25]
Interval2...
[15, 70]

Our IntervalArray...
<IntervalArray>
[[10, 25], [15, 70]]
Length: 2, dtype: interval[int64, both]

Our IntervalArray length...
Int64Index([15, 55], dtype='int64')

Checking whether the intervals is closed...
Both

Updated on: 12-Oct-2021

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements