gpt4 book ai didi

python - Pandas Groupby Dates,然后是 Group 的 Cumprod?

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:42 24 4
gpt4 key购买 nike

我有一个带有日期时间的值列表:

     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 列表,如果组 bin 为空,则 cumprod 为 1。

我目前的方法是计算第一个和最后一个时间戳,然后使用 linspace 计算等间隔的日期时间 bin,这就是我卡住的地方:

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 但我无法获得 freq 值来输出等间隔的日期时间组。我尝试的另一个解决方案是将日期时间转换为纪元,然后使用 np.digitize 按 bins 进行分类。但这也没有成功。感谢任何帮助,也欢迎使用 Numpy 解决方案。

最佳答案

您可以使用 pd.cut 轻松指定您的 bin。然后你需要groupby + prod

df.groupby(pd.cut(df.Datetime, bins=5, right=False)).Val.prod()

输出:

Datetime
[2017-01-01 15:00:00, 2017-05-09 14:24:00) 6
[2017-05-09 14:24:00, 2017-09-14 13:48:00) 1
[2017-09-14 13:48:00, 2018-01-20 13:12:00) 1
[2018-01-20 13:12:00, 2018-05-28 12:36:00) 6
[2018-05-28 12:36:00, 2018-10-04 03:21:25.200000) 9
Name: Val, dtype: int64

我们会自动得到您想要的缺失组被 1 填充的行为,因为使用 prod,空 Seriesndarrays 乘以 1。

import numpy as np

np.prod(pd.Series())
#1.0

np.prod(np.ndarray(shape=0))
#1.0

关于python - Pandas Groupby Dates,然后是 Group 的 Cumprod?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com