我们可以应用30D每月滚动总和操作,如下所示:
df.rolling("30D").sum()然而,我如何才能以类似的方式实现一个月至今(甚至年初至今)的滚动总和呢?月初至今意味着我们只从月初到当前日期(或行)进行求和?
发布于 2021-10-08 10:59:11
考虑以下数据库:
Year Month week Revenue
0 2020 1 1 10
1 2020 1 2 20
2 2020 1 3 10
3 2020 1 4 20
4 2020 2 1 10
5 2020 2 2 20
6 2020 2 3 10
7 2020 2 4 20
8 2020 3 1 10
9 2020 3 2 20
10 2020 3 3 10
11 2020 3 4 20
12 2021 1 1 10
13 2021 1 2 20
14 2021 1 3 10
15 2021 1 4 20
16 2021 2 1 10
17 2021 2 2 20
18 2021 2 3 10
19 2021 2 4 20
20 2021 3 1 10
21 2021 3 2 20
22 2021 3 3 10
23 2021 3 4 20您可以组合使用group_by + cumsum来获得您想要的内容:
df['Year_To_date'] = df.groupby('Year')['Revenue'].cumsum()
df['Month_To_date'] = df.groupby(['Year', 'Month'])['Revenue'].cumsum()结果:
Year Month week Revenue Year_To_date Month_To_date
0 2020 1 1 10 10 10
1 2020 1 2 20 30 30
2 2020 1 3 10 40 40
3 2020 1 4 20 60 60
4 2020 2 1 10 70 10
5 2020 2 2 20 90 30
6 2020 2 3 10 100 40
7 2020 2 4 20 120 60
8 2020 3 1 10 130 10
9 2020 3 2 20 150 30
10 2020 3 3 10 160 40
11 2020 3 4 20 180 60
12 2021 1 1 10 10 10
13 2021 1 2 20 30 30
14 2021 1 3 10 40 40
15 2021 1 4 20 60 60
16 2021 2 1 10 70 10
17 2021 2 2 20 90 30
18 2021 2 3 10 100 40
19 2021 2 4 20 120 60
20 2021 3 1 10 130 10
21 2021 3 2 20 150 30
22 2021 3 3 10 160 40
23 2021 3 4 20 180 60请注意,只有当数据模型中有周/日期列时,Month-to-date才有意义。
EXTRAS: cumsum的目标是计算不同时期的累计和。然而,如果原始数据帧的索引没有按期望的顺序排序,则会根据组内的原始索引计算cumsum,这是因为Pandas是按行索引顺序操作的。
因此,首先需要按所需的顺序(年、月、周或日期)对数据帧进行排序,然后重置索引以匹配感兴趣变量的顺序。现在,输出按时间顺序按时段组进行求和。
df=df.sort_values(['Year', 'Month','Week']).reset_index(drop=True)https://stackoverflow.com/questions/69494272
复制相似问题