Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count the number of zeros if they lie between ones

I have dataframe

ID   A  B  C
60   0  1  1
120  0  1  1
180  0  1  1
240  0  0  0
300  0  0  0 
360  1  1  0
420  1  1  1
480  0  0  0
540  0  0  0 
600  0  0  0
660  0  0  0
720  1  1  1
780  1  0  1
840  0  0  0
900  0  0  0 

How to count the number of zeros only between 1

in this example, the answer should be [4] in A, [2,4] in B, [3,4] in C

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could you help me, please?

i have seen this option, but it does not fit, since it counts all zeros in a row. And I need to count zeros only between 1. Please help.

>Solution :

You can try something like bfill and ffill then groupby the result

s = (df.mask(df==0).ffill() == df.mask(df==0).bfill()) & (df==0)
s = s.apply(lambda x : x[x].groupby((~x).cumsum()).count().tolist())
ID        []
A        [4]
B     [2, 4]
C     [3, 4]
dtype: object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading