我有一小时一分钟的数据,我们在 5 分钟的时间段内重新采样:(在生产中,我们无法控制收到的数据帧。这会生成一个样本。)
import numpy as np
import pandas as pd
rng = pd.date_range('7/29/2018 17:00', periods=61, freq='min')
ts = pd.DataFrame(np.ones(len(rng)), index=rng)
five_min_bins = ts.resample('5min').sum()
这(正确地)给出了一个从 18:00 开始的垃圾箱:
five_min_bins[-3:]
Out[]:
0
2018-07-29 17:50:00 5.0
2018-07-29 17:55:00 5.0
2018-07-29 18:00:00 1.0
将最后一个数据点插入前一个数据箱的好方法是什么?
到目前为止我想出的最好的方法看起来很老套:
# hack, this question is how to improve this piece of code.
import datetime
ts = ts.reset_index(drop=False)
ts['index'].iloc[-1] = ts['index'].iloc[-1] - datetime.timedelta(milliseconds=1)
ts = ts.set_index('index')
它有效。但有人知道更优雅的解决方案吗?
ts[-1:]
Out[]:
level_0 0
index
2018-07-29 17:59:59.999 60 1.0
ts.resample('5min').sum()[-3:]
Out[]:
level_0 0
index
2018-07-29 17:45:00 235 5.0
2018-07-29 17:50:00 260 5.0
2018-07-29 17:55:00 345 6.0
最佳答案
类似的想法:
ts.index = ts.index[:-1].union([ts.index[-1] - pd.Timedelta(1, unit='ms')])
five_min_bins = ts.resample('5min').sum()
print (five_min_bins)
0
2018-07-29 17:00:00 5.0
2018-07-29 17:05:00 5.0
2018-07-29 17:10:00 5.0
2018-07-29 17:15:00 5.0
2018-07-29 17:20:00 5.0
2018-07-29 17:25:00 5.0
2018-07-29 17:30:00 5.0
2018-07-29 17:35:00 5.0
2018-07-29 17:40:00 5.0
2018-07-29 17:45:00 5.0
2018-07-29 17:50:00 5.0
2018-07-29 17:55:00 6.0
关于python - 如何更新 pandas 数据框的日期时间索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51577437/