根据条件Pandas重置累计和

2024-06-16 15:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,比如:

customer spend hurdle 
A         20    50      
A         31    50      
A         20    50      
B         50    100     
B         51    100    
B         30    100     

我想计算累计的附加列,当累计总和大于或等于以下障碍时,将基于同一客户重置:

^{pr2}$

我在pandas中使用了cumsum和{},但我不知道如何根据条件重置它。在

以下是我当前使用的代码:

df1['cum_sum'] = df1.groupby(['customer'])['spend'].apply(lambda x: x.cumsum())

我知道这只是一个正常的累积总和。非常感谢你的帮助。在


Tags: 数据代码pandas客户customer条件重置df1
2条回答

一种方法是下面的代码。但这是一个非常低效和不雅观的单行线。在

df1.groupby('customer').apply(lambda x: (x['spend'].cumsum() *(x['spend'].cumsum() > x['hurdle']).astype(int).shift(-1)).fillna(x['spend']))

有更快捷的方法。这里有一个效率低下的apply方法是。在

In [3270]: def custcum(x):
      ...:     total = 0
      ...:     for i, v in x.iterrows():
      ...:         total += v.spend
      ...:         x.loc[i, 'cum'] = total
      ...:         if total >= v.hurdle:
      ...:            total = 0
      ...:     return x
      ...:

In [3271]: df.groupby('customer').apply(custcum)
Out[3271]:
  customer  spend  hurdle    cum
0        A     20      50   20.0
1        A     31      50   51.0
2        A     20      50   20.0
3        B     50     100   50.0
4        B     51     100  101.0
5        B     30     100   30.0

您可以考虑使用cythonnumba来加速custcum


[更新]

Ido s答案的改进版本。在

^{pr2}$

相关问题 更多 >