2

I'm trying to figure out the fastest way to find the first zero element along the second axis of a 2d NumPy array ignoring the leading block of zeros.

For example, I have following array:

a = np.array([[ 0. ,  0. ,  0. ],
       [ 0. ,  3. ,  0. ],
       [ 2. ,  0. ,  0. ],
       [ 0. ,  1.7,  1.5],
       [ 1. ,  1.5,  1.6]])

and what I would like to get is:

array([3, 2, 4])

In fact, ignoring all the leading zeros. This could be achieved in a for loop counting the number of leading zeros and subsequently slicing each column, it however looks pretty ugly and not so NumPy oriented.

6
  • 2
    Why that last element as 4? Commented Jul 27, 2017 at 16:09
  • because I'm ignoring the first 3 zeros and the array does not contain any other 0 element Commented Jul 27, 2017 at 16:10
  • Am I missing something? It does contain additional 0 elements. I still don't see how you can arrive at 4 for the last element. Can you look over your post and make sure your code is correct? Commented Jul 27, 2017 at 16:17
  • 1
    @AMagoon I am guessing its like an invalid specifier, i.e. if no second island of 0s found, output the last index. David can you confirm/comment on this? Commented Jul 27, 2017 at 16:20
  • 1
    @A Magoon, the code is correct. Sorry, perhaps I had to explain better this. The explanation is in @Divakar's comment Commented Jul 27, 2017 at 16:23

1 Answer 1

1

With a play of masks -

def first_zero_index_along_cols(a):
    m1 = a==0
    m2 = (~m1).cumsum(0)>0
    mask = m1 & m2
    return np.where(mask.any(0), mask.argmax(0), a.shape[0]-1)

Sample runs -

Case #1 :

In [503]: a
Out[503]: 
array([[ 0. ,  0. ,  0. ],
       [ 0. ,  3. ,  0. ],
       [ 2. ,  0. ,  0. ],
       [ 0. ,  1.7,  1.5],
       [ 1. ,  1.5,  1.6]])

In [504]: first_zero_index_along_cols(a)
Out[504]: array([3, 2, 4])

Case #2 :

In [505]: a[2:,1] = 0

In [506]: a
Out[506]: 
array([[ 0. ,  0. ,  0. ],
       [ 0. ,  3. ,  0. ],
       [ 2. ,  0. ,  0. ],
       [ 0. ,  0. ,  1.5],
       [ 1. ,  0. ,  1.6]])

In [507]: first_zero_index_along_cols(a)
Out[507]: array([3, 2, 4])

Case #3 :

In [508]: a[:,1] = 0

In [509]: a
Out[509]: 
array([[ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ],
       [ 2. ,  0. ,  0. ],
       [ 0. ,  0. ,  1.5],
       [ 1. ,  0. ,  1.6]])

In [510]: first_zero_index_along_cols(a)
Out[510]: array([3, 4, 4])
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.