【发布时间】:2018-11-04 05:29:41
【问题描述】:
我有一个包含日期时间的值列表:
Datetime Val
[[2017-01-01 15:00:00, 2],
[2017-02-05 19:00:00, 3],
[2018-04-22 15:00:00, 6],
[2018-08-02 13:00:00, 3],
[2018-10-03 12:00:00, 3]]
我想按日期时间将值分组到 N 个等间距的 bin 中,然后获取每个组的 vals cumprod 列表,如果 group bin 为空,则 cumprod 为 1。
我目前的方法是计算第一个和最后一个时间戳,然后使用 linspace 计算等距的日期时间箱,这就是我卡住的地方:
n = 5 # 5 equally sized bins
start = pd.Timestamp(df.iloc[0]['datetime'])
end = pd.Timestamp(df.iloc[-1]['datetime'])
bins = np.linspace(start.value, end.value, n+1) # n+1 as linspace is right bound including
groups = pd.to_datetime(bins).values
返回:
['2017-01-01T15:00:00.000000000' '2017-05-09T14:24:00.000000000'
'2017-09-14T13:48:00.000000000' '2018-01-20T13:12:00.000000000'
'2018-05-28T12:36:00.000000000' '2018-10-03T12:00:00.000000000']
输出具有 5 个等间距的 bin,上面给出的示例值可以是例如:
output = [2*3, 1, 1, 6, 3*3] # 1 if there is no "Val" for a bin
有没有有效/干净的方法来解决这个问题?我研究了 pd.Grouper 但我无法让频率值工作以输出等距的日期时间组。我尝试的另一个解决方案是将日期时间转换为纪元,然后使用 np.digitize 按箱分类。但这也没有成功。感谢任何帮助,也欢迎 Numpy 解决方案。
【问题讨论】:
-
你真的需要每个bin的累积产品,还是只需要产品?我觉得这不是你想要的,但是像
df.resample('10D').prod().replace(0, 1)这样的东西呢?