Home > Software design >  Count number of gaps in a 1D numpy array
Count number of gaps in a 1D numpy array

Time:06-08

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.

CodePudding user response:

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

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

output: 4

  • Related