Python Pandas:几个月来每天都做 cumsum
Python Pandas: Doing cumsum for each day for months
我有一个数据框如下
Storeid Year-Month Date Amount
111 01-2016 2016-01-29 10
111 01-2016 2016-01-30 15
111 02-2016 2016-02-03 20
111 02-2016 2016-02-10 17
111 02-2016 2016-02-15 18
111 03-2016 2016-03-02 12
112 01-2016 2016-01-25 14
112 01-2016 2016-01-29 12
...
我想要的输出是这个
Storeid Year-Month Date Amount
111 01-2016 2016-01-29 10
111 01-2016 2016-01-30 25
111 02-2016 2016-02-03 20
111 02-2016 2016-02-10 37
111 02-2016 2016-02-15 55
111 03-2016 2016-03-02 12
112 01-2016 2016-01-25 14
112 01-2016 2016-01-29 26
...
该值在每个月后重置,并再次从 0 开始。我尝试从 pandas 执行 cumsum
函数,但它会尝试在整个数据框中执行此操作。我如何限制它每月执行一次?
目标是找到 "Given a date, which store reached their sales target as of that date for the month"。销售目标是 $1000
你可以做到 groupby.cumsum
:
df['AmountToDate'] = df.groupby(['Storeid', 'Year-Month']).Amount.cumsum()
df
Update:提取对应的行,可以使用groupby.apply(...cumsum..)
,可以做更多的自定义操作:
(df.groupby(['Storeid', 'Year-Month'], as_index=False, group_keys=False)
.apply(lambda g: g.assign(Amount = g.Amount.cumsum())[lambda x: x.Amount >= 25].head(1)))
这是如何工作的?
groupby.apply
表示apply
方法中的lambda
表达式分别应用于每个组(这里是Storeid和Year-Month的唯一组合);
- 传递给lambda表达式的参数g是一个子数据框,有唯一的storeid + Year-Month(组变量),对每个数据框计算
Amount
cumsum,过滤掉cumsum >= 的行使用 head(1)
. 定位并占据第一行
我有一个数据框如下
Storeid Year-Month Date Amount
111 01-2016 2016-01-29 10
111 01-2016 2016-01-30 15
111 02-2016 2016-02-03 20
111 02-2016 2016-02-10 17
111 02-2016 2016-02-15 18
111 03-2016 2016-03-02 12
112 01-2016 2016-01-25 14
112 01-2016 2016-01-29 12
...
我想要的输出是这个
Storeid Year-Month Date Amount
111 01-2016 2016-01-29 10
111 01-2016 2016-01-30 25
111 02-2016 2016-02-03 20
111 02-2016 2016-02-10 37
111 02-2016 2016-02-15 55
111 03-2016 2016-03-02 12
112 01-2016 2016-01-25 14
112 01-2016 2016-01-29 26
...
该值在每个月后重置,并再次从 0 开始。我尝试从 pandas 执行 cumsum
函数,但它会尝试在整个数据框中执行此操作。我如何限制它每月执行一次?
目标是找到 "Given a date, which store reached their sales target as of that date for the month"。销售目标是 $1000
你可以做到 groupby.cumsum
:
df['AmountToDate'] = df.groupby(['Storeid', 'Year-Month']).Amount.cumsum()
df
Update:提取对应的行,可以使用groupby.apply(...cumsum..)
,可以做更多的自定义操作:
(df.groupby(['Storeid', 'Year-Month'], as_index=False, group_keys=False)
.apply(lambda g: g.assign(Amount = g.Amount.cumsum())[lambda x: x.Amount >= 25].head(1)))
这是如何工作的?
groupby.apply
表示apply
方法中的lambda
表达式分别应用于每个组(这里是Storeid和Year-Month的唯一组合);- 传递给lambda表达式的参数g是一个子数据框,有唯一的storeid + Year-Month(组变量),对每个数据框计算
Amount
cumsum,过滤掉cumsum >= 的行使用head(1)
. 定位并占据第一行