Python Pandas - Get the length from the IntervalIndex

To get the length from the IntervalIndex, use the interval.length property in Pandas. The length represents the width of each interval in the IntervalIndex.

Syntax

IntervalIndex.length

Creating an IntervalIndex

First, let's create an IntervalIndex using from_arrays() method ?

import pandas as pd

# Create IntervalIndex from left and right arrays
interval = pd.IntervalIndex.from_arrays([10, 15, 20], [20, 25, 30])

# Display the interval
print("IntervalIndex...")
print(interval)
IntervalIndex...
IntervalIndex([(10, 20], (15, 25], (20, 30]], dtype='interval[int64, right]')

Getting the Length

Use the length property to get the width of each interval ?

import pandas as pd

# Create IntervalIndex
interval = pd.IntervalIndex.from_arrays([10, 15, 20], [20, 25, 30])

# Display the interval length
print("IntervalIndex length...")
print(interval.length)
IntervalIndex length...
Index([10, 10, 10], dtype='int64')

Complete Example

Here's a complete example showing IntervalIndex creation, length calculation, and midpoint ?

import pandas as pd

# Create IntervalIndex
interval = pd.IntervalIndex.from_arrays([10, 15, 20], [20, 25, 30])

# Display the interval
print("IntervalIndex...")
print(interval)

# Display the interval length
print("\nIntervalIndex length...")
print(interval.length)

# Return the midpoint of the Interval
print("\nThe midpoint for the Interval...")
print(interval.mid)
IntervalIndex...
IntervalIndex([(10, 20], (15, 25], (20, 30]], dtype='interval[int64, right]')

IntervalIndex length...
Index([10, 10, 10], dtype='int64')

The midpoint for the Interval...
Index([15.0, 20.0, 25.0], dtype='float64')

Key Points

  • The length property returns the width of each interval (right - left)
  • All intervals in this example have the same length of 10 units
  • The result is returned as an Index object with the same data type as the interval bounds

Conclusion

The length property provides a convenient way to calculate the width of intervals in a Pandas IntervalIndex. It returns an Index containing the length of each interval, calculated as the difference between right and left bounds.

Updated on: 2026-03-26T16:58:24+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements