Python Pandas - Return an IntervalArray identical to the current one but closed on the specified side

To return an IntervalArray identical to the current one but closed on the specified side, use the array.set_closed() method. This method allows you to change how intervals handle their endpoints without modifying the underlying data.

Understanding Interval Closures

Intervals can be closed in different ways:

  • right: (a, b] − excludes left endpoint, includes right
  • left: [a, b) − includes left endpoint, excludes right
  • both: [a, b] − includes both endpoints
  • neither: (a, b) − excludes both endpoints

Creating an IntervalArray

First, let's create an IntervalArray from breaks ?

import pandas as pd

# Construct a new IntervalArray from an array-like of splits
array = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3, 4, 5])

# Display the IntervalArray
print("Original IntervalArray:")
print(array)
print(f"Closure type: {array.closed}")
Original IntervalArray:
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]]
Length: 5, dtype: interval[int64, right]
Closure type: right

Changing Interval Closure

Use set_closed() to create an identical array with different closure ?

import pandas as pd

array = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3, 4, 5])

# Change to 'both' closure
both_closed = array.set_closed('both')
print("Both endpoints closed:")
print(both_closed)

# Change to 'left' closure
left_closed = array.set_closed('left')
print("\nLeft endpoint closed:")
print(left_closed)

# Change to 'neither' closure
neither_closed = array.set_closed('neither')
print("\nNeither endpoint closed:")
print(neither_closed)
Both endpoints closed:
<IntervalArray>
[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]
Length: 5, dtype: interval[int64, both]

Left endpoint closed:
<IntervalArray>
[[0, 1), [1, 2), [2, 3), [3, 4), [4, 5)]
Length: 5, dtype: interval[int64, left]

Neither endpoint closed:
<IntervalArray>
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
Length: 5, dtype: interval[int64, neither]

Comparison of Closure Types

Closure Type Notation Left Endpoint Right Endpoint
right (a, b] Excluded Included
left [a, b) Included Excluded
both [a, b] Included Included
neither (a, b) Excluded Excluded

Conclusion

The set_closed() method creates a new IntervalArray with the same intervals but different closure behavior. This is useful for mathematical operations where endpoint inclusion matters.

Updated on: 2026-03-26T16:11:57+05:30

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements