我的 Pandas 版本是 0.18,我有一个如下所示的分钟数据:
Time
2009-01-30 09:30:00 85.11 100.11
2009-01-30 09:39:00 84.93 100.05
2009-01-30 09:40:00 84.90 100.00
2009-01-30 09:45:00 84.91 99.94
2009-01-30 09:48:00 84.81 99.90
2009-01-30 09:55:00 84.78 100.00
2009-01-30 09:56:00 84.57 100.10
2009-01-30 09:59:00 84.25 100.41
2009-01-30 10:00:00 84.32 100.60
2009-01-30 10:06:00 84.23 101.49
2009-01-30 10:09:00 84.15 101.47
我只想使用 9:30 和 16:00 的数据,并以 78 分钟的间隔重新采样数据(即将 9:30 和 16:00 之间的时间分成 5 个相等的部分)。我的代码如下所示:
Data= Data.between_time('9:30','16:00')
tframe = '78T'
hourlym = Data.resample(tframe, base=30).mean()
输出:
Time
2009-01-30 08:18:00 85.110000 100.110000
2009-01-30 09:36:00 83.950645 101.984516
2009-01-30 10:54:00 83.372294 103.093824
2009-01-30 12:12:00 83.698624 102.566897
2009-01-30 13:30:00 83.224397 103.076667
2009-01-30 14:48:00 82.641167 104.114667
2009-01-30 16:06:00 NaN NaN
2009-01-30 17:24:00 NaN NaN
2009-01-30 18:42:00 NaN NaN
如您所见,pandas 忽略了我的基本参数,而我的输出表从 8:18 开始,我相信这是因为 pandas 寻求如何将我的整个数据正确拆分为 78 分钟,并且由于您不能将 24 小时平均分为 78 分钟,因此会发生这种奇怪的行为.有没有可能强制 Pandas 从第一天的9:30开始重新采样?或者在重新采样时仅在特定时间工作?
最佳答案
base
参数适用于午夜,因此在您的情况下,采样从 00:30 开始并从那里添加 78 分钟的增量。我看到两个选项。
选项 1 :
弄清楚是什么base
应用于午夜应该是为了到达 9:30(在这种情况下 24
):
Data.resample(tframe, base=24)
选项 2 :
自己生成日期时间索引,并使用
reindex
重新采样:index = pd.date_range('2009-01-30 09:30:00', '2009-01-30 16:00:00', freq='78min')
Data.reindex(index=index)
编辑 :对于多天,您需要自己生成时间戳。
index_date = pd.date_range('2016-04-01', '2016-04-04')
index_date = pd.Series(index_date)
index_time = pd.date_range('09:30:00', '16:00:00', freq='78min')
index_time = pd.Series(index_time.time)
index = index_date.apply(
lambda d: index_time.apply(
lambda t: datetime.combine(d, t)
)
).unstack().sort_values().reset_index(drop=True)
下面是代码的作用:
apply
属性(property)。 unstack
并对时间戳进行排序(最后重置索引以摆脱沿途生成的无用索引)。 由此产生的
index
可用于重新索引,如最初的选项 2:Data.reindex(index=index)
关于Python Pandas,仅重采样特定时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36977103/