gpt4 book ai didi

python - 根据条件 Pandas 重置累积总和

转载 作者:太空狗 更新时间:2023-10-30 02:54:12 25 4
gpt4 key购买 nike

我有一个像这样的数据框:

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

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

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

我在 pandas 中使用了 cumsumgroupby 但我不知道如何根据条件重置它。

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

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

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

最佳答案

可能有更快、更有效的方法。这是一种低效的 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 答案的改进版本。

In [3276]: s = df.groupby('customer').spend.cumsum()

In [3277]: np.where(s > df.hurdle.shift(-1), s, df.spend)
Out[3277]: array([ 20, 51, 20, 50, 101, 30], dtype=int64)

关于python - 根据条件 Pandas 重置累积总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46784265/

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