Python Pandas - Construct an IntervalArray from an array of splits


To construct an IntervalArray from an array of splits, use the pandas.arrays.IntervalArray.from_breaks().

At first, import the required libraries −

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 intervals −

print("Our IntervalArray...\n",array)

Getting the length of IntervalArray −

print("\nOur IntervalArray length...\n",array.length)

Example

Following is the code −

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("Our 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)

# midpoint of each Interval in the IntervalArray as an Index
print("\nThe midpoint of each interval in the IntervalArray...\n",array.mid)

Output

This will produce the following code −

Our IntervalArray...
<IntervalArray>
[(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]]
Length: 5, dtype: interval[int64, right]

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

The midpoint of each interval in the IntervalArray...
Float64Index([0.5, 1.5, 2.5, 3.5, 4.5], dtype='float64')

Updated on: 13-Oct-2021

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements