Skip to content
Advertisement

Count number of consecutive True in column, restart when False

I work with the following column in a pandas df:

JavaScript

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

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

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement