Skip to content
Advertisement

Count number of consecutive True in column, restart when False

I work with the following column in a pandas df:

A
True
True
True
False
True
True

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:

A      B
True   1
True   2
True   3
False  0
True   1
True   2

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

df['B'] = df['A'].groupby((~df['A']).cumsum()).cumsum()

       A  B
0   True  1
1   True  2
2   True  3
3  False  0
4   True  1
5   True  2
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement