I work with the following column in a pandas df:
JavaScript
x
8
1
A
2
True
3
True
4
True
5
False
6
True
7
True
8
I want to add column B that counts the number of consecutive “True” in A. I want to restart everytime a “False” comes up. Desired output:
JavaScript
1
8
1
A B
2
True 1
3
True 2
4
True 3
5
False 0
6
True 1
7
True 2
8
Advertisement
Answer
Using cumsum
identify the blocks of rows where the values in column A
stays True
, then group the column A
on these blocks and calculate cumulative sum to assign ordinal numbers
JavaScript
1
2
1
df['B'] = df['A'].groupby((~df['A']).cumsum()).cumsum()
2
JavaScript
1
8
1
A B
2
0 True 1
3
1 True 2
4
2 True 3
5
3 False 0
6
4 True 1
7
5 True 2
8