ShanN
ShanN

Reputation: 943

Pandas cummulative sum based on True/False condition

I'm using python and need to solve the dataframe as cumsum() the value until the boolean column change its value from True to False. How to solve this task?

    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
....

Thank all!

Upvotes: 0

Views: 229

Answers (1)

moys
moys

Reputation: 8033

You can try this

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

Output

    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

Upvotes: 3

Related Questions