Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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() method. This creates intervals from breakpoints where each consecutive pair of values forms an interval.
Syntax
pandas.arrays.IntervalArray.from_breaks(breaks, closed='right', copy=False, dtype=None)
Creating IntervalArray from Breaks
First, import the required library ?
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)
Our IntervalArray... <IntervalArray> [(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]] Length: 5, dtype: interval[int64, right]
Accessing Properties
You can access various properties of the IntervalArray ?
import pandas as pd
array = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3, 4, 5])
# Getting the length of each interval
print("Length of each interval...\n", array.length)
# Getting the midpoint of each interval
print("\nMidpoint of each interval...\n", array.mid)
# Getting the left and right endpoints
print("\nLeft endpoints...\n", array.left)
print("\nRight endpoints...\n", array.right)
Length of each interval... Index([1, 1, 1, 1, 1], dtype='int64') Midpoint of each interval... Index([0.5, 1.5, 2.5, 3.5, 4.5], dtype='float64') Left endpoints... Index([0, 1, 2, 3, 4], dtype='int64') Right endpoints... Index([1, 2, 3, 4, 5], dtype='int64')
Closed Parameter Options
You can control which side of the interval is closed ?
import pandas as pd
# Right-closed intervals (default)
right_closed = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3], closed='right')
print("Right-closed:", right_closed)
# Left-closed intervals
left_closed = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3], closed='left')
print("Left-closed:", left_closed)
# Both sides closed
both_closed = pd.arrays.IntervalArray.from_breaks([0, 1, 2, 3], closed='both')
print("Both closed:", both_closed)
Right-closed: <IntervalArray> [(0, 1], (1, 2], (2, 3]] Length: 3, dtype: interval[int64, right] Left-closed: <IntervalArray> [[0, 1), [1, 2), [2, 3)] Length: 3, dtype: interval[int64, left] Both closed: <IntervalArray> [[0, 1], [1, 2], [2, 3]] Length: 3, dtype: interval[int64, both]
Conclusion
Use IntervalArray.from_breaks() to create intervals from breakpoints. The closed parameter controls interval boundaries, and you can access properties like length, mid, left, and right for further analysis.
Advertisements
