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

Count number of gaps in a 1D numpy array

I want to count the number of gaps in a numpy array. In this case the consecutive zeros count as one gap.

array = np.array([   0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
        1692, 1692, 1692, 1692, 1692, 1692, 1692, 2458, 2458, 2458, 2458,
        2458, 2458, 2458,    0,    0,    0, 3956, 3956, 3956, 3956, 3956,
        3956, 3956,    0,    0,    0,    0, 5431, 5431, 5431, 5431, 5431,
        5431, 5431,    0,    0,    0,    0,    0,    0,    0,    0,    0])

In the above array there are 4 gaps, so my output should be 4.

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

>Solution :

You can use a boolean array and count the values that True when the previous one is False:

a = array==0
(a&~np.r_[[False],a[:-1]]).sum()

output: 4

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