Python - 为区间数据创建 Pandas 数组
要为区间数据创建 Pandas 数组,请使用 pandas.arrays.IntervalArray() 方法。首先,导入所需的库 −
import pandas as pd
创建两个 Interval 对象 −
interval1 = pd.Interval(10, 30) interval2 = pd.Interval(30, 70)
显示区间 −
print("Interval1...\n",interval1) print("Interval2...\n",interval2)
从 Interval 对象构建一个新的 IntervalArray −
array = pd.arrays.IntervalArray([interval1,interval2])
示例
以下为代码 −
import pandas as pd # Create two Interval objects interval1 = pd.Interval(10, 30) interval2 = pd.Interval(30, 70) # display the intervals print("Interval1...\n",interval1) print("Interval2...\n",interval2) # 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)
输出
将生成以下代码 −
Interval1... (10, 30] Interval2... (30, 70] Our IntervalArray... <IntervalArray> [(10, 30], (30, 70]] Length: 2, dtype: interval[int64, right] Our IntervalArray length... Int64Index([20, 40], dtype='int64')
广告