基于正确/错误条件的熊猫累积总和

时间:2020-02-05 04:44:19

标签: python pandas

我正在使用python,需要将数据框解析为cumsum(),直到布尔列将其值从True更改为False为止。如何解决此任务?

    Bool       Value      Expected_cumsum
0   False        1                1
1   False        2                3
2   False        4                7
3   True         1                8       
4   False        3                3  << reset from here
5   False        5                8
6   True         2                10
....

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以尝试

a = df.Bool.eq(True).cumsum().shift().fillna(0)
df['Expected_cumsum']= df.groupby(a)['Value'].cumsum()
df

输出

    Bool    Value   Expected_cumsum
0   False   1        1
1   False   2        3
2   False   4        7
3   True    1        8
4   False   3        3
5   False   5        8
6   True    2        10