hkbgner
hkbgner

Reputation: 331

vectorized method to count number of special instances in numpy array

Let's say I have an array that is

test = np.array([0,2,1,5,3,6,10,0,0,3,2,3,0,0,7,3,6,2,0,0,3,5,4,6])

What I want to know is the number of times when the next value is non-zero when the previous value is zero; so for the above array I should have 4.

I wrote a function that does that but it is performing very slow. Is there any vectorized function that I should re-write it into?

def count_instance(array):
    return int(array[0] > 0) + sum(int(array[i] > 0 and array[i-1] == 0) for i in range(1,array.shape[0]))

Upvotes: 2

Views: 49

Answers (1)

Divakar
Divakar

Reputation: 221584

One-liner with slicing -

((test[:-1]==0) & (test[1:]!=0)).sum()

Another way with re-usage of the same mask -

m = test==0
((m[:-1]) & (~m[1:])).sum()

Upvotes: 1

Related Questions