2

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]))

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.