Python Pandas IntervalIndex - Return an ndarray of tuples of the form (left, right)

To return an ndarray of tuples of the form (left, right), use the to_tuples() method in Pandas. This method converts an IntervalArray or IntervalIndex into an array of tuples representing the interval boundaries.

Creating an IntervalArray

First, let's create an IntervalArray using from_breaks() ?

import pandas as pd

# Create IntervalArray from range breaks
index = pd.arrays.IntervalArray.from_breaks(range(5))
print("IntervalArray...")
print(index)
IntervalArray...
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4]]
Length: 4, dtype: interval[int64, right]

Converting to Tuples

Use the to_tuples() method to get an ndarray of tuples ?

import pandas as pd

# Create IntervalArray
index = pd.arrays.IntervalArray.from_breaks(range(5))

# Convert to ndarray of tuples
tuples_array = index.to_tuples()
print("The ndarray of Tuples...")
print(tuples_array)
print("Type:", type(tuples_array))
The ndarray of Tuples...
[(0, 1) (1, 2) (2, 3) (3, 4)]
Type: <class 'numpy.ndarray'>

Complete Example

Here's a complete example showing IntervalArray creation and tuple conversion ?

import pandas as pd

# Create IntervalArray
index = pd.arrays.IntervalArray.from_breaks(range(5))

# Display the interval
print("IntervalArray...")
print(index)

# Display the interval length
print("\nInterval lengths...")
print(index.length)

# Return the ndarray of Tuples
print("\nThe ndarray of Tuples...")
print(index.to_tuples())
IntervalArray...
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4]]
Length: 4, dtype: interval[int64, right]

Interval lengths...
Int64Index([1, 1, 1, 1], dtype='int64')

The ndarray of Tuples...
[(0, 1) (1, 2) (2, 3) (3, 4)]

Key Points

  • The to_tuples() method returns a NumPy ndarray
  • Each tuple contains (left, right) boundary values
  • The original interval notation uses square brackets to indicate closed/open intervals
  • The tuple format simplifies accessing individual boundary values

Conclusion

The to_tuples() method provides an efficient way to convert IntervalArray objects into NumPy arrays of tuples. This is useful when you need to work with interval boundaries as separate left and right values.

Updated on: 2026-03-26T17:20:18+05:30

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements