gpt4 book ai didi

python - pandas 计算每个日期最近 7 天的值

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:54 26 4
gpt4 key购买 nike

有两个数据框。首先是这样的:

print df1

id date month is_buy
0 17 2015-01-16 2015-01 1
1 17 2015-01-26 2015-01 1
2 17 2015-01-27 2015-01 1
3 17 2015-02-11 2015-02 1
4 17 2015-03-14 2015-03 1
5 18 2015-01-28 2015-01 1
6 18 2015-02-12 2015-02 1
7 18 2015-02-25 2015-02 1
8 18 2015-03-04 2015-03 1

在第二个数据框中,有一些从第一个数据框中按月汇总的数据:

df2 = df1[df1['is_buy'] == 1].groupby(['id', 'month']).agg({'is_buy': np.sum})

print df2

id month buys
0 17 2015-01 3
1 17 2015-02 1
2 17 2015-03 1
3 18 2015-01 1
4 18 2015-02 2
5 18 2015-03 1

我正在尝试获取名为“last_week_buys”的新 df2 列,其中包含从每个 df1['month'] 的第一天算起的过去 7 天的总购买量。换句话说,我想得到这个:

        id    month       buys    last_week_buys
0 17 2015-01 3 NaN
1 17 2015-02 1 2
2 17 2015-03 1 0
3 18 2015-01 1 NaN
4 18 2015-02 2 1
5 18 2015-03 1 1

有什么想法可以得到这个专栏吗?

最佳答案

这可以通过一些日期操作魔法和分组来完成:

# datetimeindex makes convenient manipulations
date = pd.DatetimeIndex(df1['date'])

# compute df2: totals by month
df1['month'] = date.to_period('M')
df2 = df1[df1['is_buy'] == 1].groupby(['id', 'month']).sum()

# compute df3: totals by last seven days
from datetime import timedelta
is_last_seven = date.to_period('M') != (date + timedelta(days=7)).to_period('M')
df3 = df1[(df1['is_buy'] == 1) & is_last_seven].groupby(['id', df1.month + 1]).sum()

# join the results
result = df2.join(df3, rsuffix='_last_seven')

结果如下:

>>> print(result)

is_buy is_buy_last_seven
id month
17 2015-01 3 NaN
2015-02 1 2
2015-03 1 NaN
18 2015-01 1 NaN
2015-02 2 1
2015-03 1 1

然后您可以根据需要填充 NaN 值。

关于python - pandas 计算每个日期最近 7 天的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33914458/

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