Python Pandas - Return an Index with entries denoting the length of each Interval in the IntervalArray

PythonServer Side ProgrammingProgramming

To return an Index with entries denoting the length of each Interval in the IntervalArray, use the array.length property.

At first, import the required libraries −

import pandas as pd

Create two Interval objects. Closed intervals set using the "closed" parameter with value "both" −

interval1 = pd.Interval(50, 75, closed='both')
interval2 = pd.Interval(65, 95, closed='both')

Construct a new IntervalArray from Interval objects −

array = pd.arrays.IntervalArray([interval1,interval2])

Display the IntervalArray −

print("\nOur 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)

Example

Following is the code −

import pandas as pd

# Create two Interval objects
# Closed intervals set using the "closed" parameter with value "both"
interval1 = pd.Interval(50, 75, closed='both')
interval2 = pd.Interval(65, 95, closed='both')

# display the intervals
print("Interval1...\n",interval1)
print("Interval2...\n",interval2)

# display the interval length
print("\nInterval1 length...\n",interval1.length)
print("\nInterval2 length...\n",interval2.length)

# Construct a new IntervalArray from Interval objects
array = pd.arrays.IntervalArray([interval1,interval2])

# Display the IntervalArray
print("\nOur 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)

Output

This will produce the following code −

Interval1...
[50, 75]
Interval2...
[65, 95]

Interval1 length...
25

Interval2 length...
30

Our IntervalArray...
<IntervalArray>
[[50, 75], [65, 95]]
Length: 2, dtype: interval[int64, both]

Our IntervalArray length...
Int64Index([25, 30], dtype='int64')
raja
Updated on 12-Oct-2021 12:34:17

Advertisements