我有一个带有日期时间索引的大型数据帧,需要将数据重新采样到10个大小相等的时段。在
到目前为止,我已经尝试找到第一个和最后一个日期来确定数据中的总天数,除以10来确定每个时段的大小,然后使用该天数重新取样。例如:
first = df.reset_index().timesubmit.min()
last = df.reset_index().timesubmit.max()
periodsize = str((last-first).days/10) + 'D'
df.resample(periodsize,how='sum')
因为periodsize是一个向下取整的整数,所以这不能保证在重采样后df中正好有10个时段。在重采样中使用float不起作用。看来要么是我遗漏了一些简单的东西,要么是我把问题搞错了。在
收益率
^{pr2}$0
-列中的值表示聚合的行数,因为原始数据帧的值为1。由于33行不能均匀地分为10组,所以4和3的模式基本上是均匀的。在解释:考虑这个更简单的数据帧:
使用
df.resample('2D', how='sum')
会给出错误的组数使用
df.resample('3D', how='sum')
可以提供正确数量的组,但是 第二组从2000-01-04
开始,它不均匀地划分数据帧 分成两个等距分组:为了做得更好,我们需要以比几天更精确的时间分辨率工作。既然
Timedelta
s有一个total_seconds
方法,让我们以秒为单位工作。所以对于上面的例子,期望的频率串应该是由于5天内有216000*2秒:
好吧,现在我们需要的是一种推广的方法。我们需要索引中的最短和最长日期:
我们多加了一天,因为这会让不同的日子变得不同。在 在上面的例子中,2000-01-05的时间戳之间只有4天 以及2000-01-01
但是,正如我们在示例中看到的,DataFrame有5行代表5 天。所以我们需要多加一天。在
现在,我们可以计算出每个等间距组的正确秒数:
这里有一种确保子时段大小相等的方法,方法是在
pd.Timedelta
上使用np.linspace()
,然后使用pd.cut
将每个ob分类到不同的bin中。在另一种较短的方法是将采样频率指定为时间增量。但问题是,正如下面所示,它提供了11个子样本,而不是10个子样本。我认为原因是
^{pr2}$resample
实施了left-inclusive/right-exclusive (or left-exclusive/right-inclusive)
子抽样方案,因此在'2015-02-03 00:00:00'的最后一个obs被视为一个单独的组。如果我们自己用pd.cut
来做,我们可以指定include_lowest=True
,这样它就可以给出10个子样本而不是11个子样本。在相关问题 更多 >
编程相关推荐