Skip to content
Advertisement

How to get the Toggle flag value and sum of rows between the flag toggle

In continuation to my previous Question I need some more help.

The dataframe is like

id  power   flag
0   20      0
1   25      0
2   26      1
3   30      1
4   18      0
5   30      0
6   19      0
7   21      1
8   23      0

I am trying to have the flag state value along with the toggle count, Means flag toggling state. The output should look like this

    Sum of power       flag_state
0   45 (20 +25)           0
1   56 (26 + 30)          1
2   67 (18 +30 +19)       0
3   21 (21)               1
4   23 (23)               0

Can someone help with this?

Advertisement

Answer

Create helper Series with shift and cumsum and aggregate sum, last remove helper first level of MultiIndex by first reset_index:

df1 = (df.groupby([df['flag'].ne(df['flag'].shift()).cumsum(), 'flag'])['power']
         .sum()
         .reset_index(level=0, drop=True)
         .reset_index(name='sum of power'))
print (df1)
   flag  sum of power
0     0            45
1     1            56
2     0            67
3     1            21
4     0            23
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement