Search code examples
pythonpandasbooleancumsum

Counting rows since condition


I have a column in Pandas which contains booleans and want to count thr rows since the last True value, something like this:

a           b
False       0
True        0
False       1
False       2 
False       3  
True        0
False       1
True        0

I could do it via a loop but it seems there must be a better way


Solution

  • a = ~df['a']
    b = a.cumsum()
    c = b-b.where(~a).ffill().fillna(1).astype(int)
    print (c)
    0    0
    1    0
    2    1
    3    2
    4    3
    5    0
    6    1
    7    0
    Name: a, dtype: int32