In continuation to my previous Question I need some more help.
The dataframe is like
JavaScript
x
11
11
1
id power flag
2
0 20 0
3
1 25 0
4
2 26 1
5
3 30 1
6
4 18 0
7
5 30 0
8
6 19 0
9
7 21 1
10
8 23 0
11
I am trying to have the flag state value along with the toggle count, Means flag toggling state. The output should look like this
JavaScript
1
7
1
Sum of power flag_state
2
0 45 (20 +25) 0
3
1 56 (26 + 30) 1
4
2 67 (18 +30 +19) 0
5
3 21 (21) 1
6
4 23 (23) 0
7
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
:
JavaScript
1
12
12
1
df1 = (df.groupby([df['flag'].ne(df['flag'].shift()).cumsum(), 'flag'])['power']
2
.sum()
3
.reset_index(level=0, drop=True)
4
.reset_index(name='sum of power'))
5
print (df1)
6
flag sum of power
7
0 0 45
8
1 1 56
9
2 0 67
10
3 1 21
11
4 0 23
12