Python Pandas - 将 IntervalArray 中每个 Interval 的中点作为索引返回
要将IntervalArray中每个Interval的中点作为索引返回,请使用array.mid属性。首先,
首先,导入所需的库-
import pandas as pd
创建两个Interval对象。使用值为“both”的“closed”参数设置的闭合区间-
interval1 = pd.Interval(50, 75, closed='both') interval2 = pd.Interval(65, 90, closed='both')
显示间隔-
print("Interval1...\n",interval1) print("Interval2...\n",interval2)
从Interval对象构造一个新的IntervalArray-
array = pd.arrays.IntervalArray([interval1,interval2])
IntervalArray中每个Interval的中点作为索引-
print("\nThe midpoint of each interval in the IntervalArray...\n",array.mid)
示例
以下是代码-
import pandas as pd #CreatetwoIntervalobjects # Closed intervals set using the "closed" 带值的参数 "both" interval1 = pd.Interval(50, 75, closed='both') interval2 = pd.Interval(65, 90, closed='both') #displaytheintervals print("Interval1...\n",interval1) print("Interval2...\n",interval2) #ConstructanewIntervalArrayfromIntervalobjects array = pd.arrays.IntervalArray([interval1,interval2]) #DisplaytheIntervalArray print("\nOur IntervalArray...\n",array) #GettingthelengthofIntervalArray #ReturnsanIndexwithentriesdenotingthelengthofeachIntervalintheIntervalArray print("\nOur IntervalArray length...\n",array.length) #midpointofeachIntervalintheIntervalArrayasanIndex print("\nThe midpoint of each interval in the IntervalArray...\n",array.mid)输出结果
这将产生以下代码-
Interval1... [50, 75] Interval2... [65, 90] Our IntervalArray... <IntervalArray> [[50, 75], [65, 90]] Length: 2, dtype: interval[int64, both] Our IntervalArray length... Int64Index([25, 25], dtype='int64') The midpoint of each interval in the IntervalArray... Float64Index([62.5, 77.5], dtype='float64')