Skip to content
Advertisement

Python pandas cumsum with reset everytime there is a 0

I have a matrix with 0s and 1s, and want to do a cumsum on each column that resets to 0 whenever a zero is observed. For example, if we have the following:

JavaScript

The result I desire is:

JavaScript

However, when I try df.cumsum() * df, I am able to correctly identify the 0 elements, but the counter does not reset:

JavaScript

Advertisement

Answer

You can use:

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