Python Pandas - Construct an IntervalArray from an array-like of tuples

The pandas.arrays.IntervalArray is a specialized array for storing intervals. You can construct an IntervalArray from an array-like of tuples using the from_tuples() method. This is useful when working with ranges, bins, or any data that represents intervals.

Basic Syntax

pandas.arrays.IntervalArray.from_tuples(data, closed='right', copy=False, dtype=None)

Creating IntervalArray from Tuples

Let's create an IntervalArray from tuples representing different intervals ?

import pandas as pd

# Construct a new IntervalArray from an array-like of tuples
array = pd.arrays.IntervalArray.from_tuples([(10, 25), (15, 70), (30, 50)])

# Display the IntervalArray
print("Our IntervalArray...")
print(array)
Our IntervalArray...
<IntervalArray>
[(10, 25], (15, 70], (30, 50]]
Length: 3, dtype: interval[int64, right]

Accessing IntervalArray Properties

IntervalArray provides several useful properties to work with intervals ?

import pandas as pd

array = pd.arrays.IntervalArray.from_tuples([(10, 25), (15, 70), (30, 50)])

# Getting the length of each interval
print("Length of each interval:")
print(array.length)

# Getting the midpoint of each interval
print("\nMidpoint of each interval:")
print(array.mid)

# Getting left and right endpoints
print("\nLeft endpoints:")
print(array.left)

print("\nRight endpoints:")
print(array.right)
Length of each interval:
Index([15, 55, 20], dtype='int64')

Midpoint of each interval:
Index([17.5, 42.5, 40.0], dtype='float64')

Left endpoints:
Index([10, 15, 30], dtype='int64')

Right endpoints:
Index([25, 70, 50], dtype='int64')

Specifying Closed Parameter

You can control whether intervals are closed on the left, right, both, or neither ?

import pandas as pd

# Create intervals with different closed parameters
left_closed = pd.arrays.IntervalArray.from_tuples([(1, 5), (3, 8)], closed='left')
both_closed = pd.arrays.IntervalArray.from_tuples([(1, 5), (3, 8)], closed='both')

print("Left closed intervals:")
print(left_closed)

print("\nBoth closed intervals:")
print(both_closed)
Left closed intervals:
<IntervalArray>
[[1, 5), [3, 8)]
Length: 2, dtype: interval[int64, left]

Both closed intervals:
<IntervalArray>
[[1, 5], [3, 8]]
Length: 2, dtype: interval[int64, both]

Parameters

Parameter Description Default
data Array-like of tuples Required
closed 'left', 'right', 'both', or 'neither' 'right'
copy Whether to copy the data False
dtype Data type for the intervals None

Conclusion

The from_tuples() method provides a convenient way to create IntervalArrays from tuple data. Use it when you need to work with interval-based data like age ranges, time periods, or numerical bins in pandas operations.

Updated on: 2026-03-26T15:56:14+05:30

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements