-1

Given an array like this

a1= np.array([0,2,0,3])

if i want to return index of the first zero I do simply:

(a1==0).argmax(axis=0)
>> 0

however for the list like this:

a2= np.array([1,2,3,3])

It returns the same thing although the array does not have any zeros.

(a2==0).argmax(axis=0)
>> 0

How can I distinguish between these situations? Is it possible to impose that if an array does not have any zeros, the algorithm should return None?

kikatuso
  • 150
  • 12
  • Does this answer your question? [Python: find position of element in array](https://stackoverflow.com/questions/27260811/python-find-position-of-element-in-array) – Pranav Hosangadi Mar 02 '21 at 21:10
  • Why does `.find` as suggested in the linked duplicate not work? In fact, if you want a numpy solution, [`np.argwhere()`](https://numpy.org/doc/stable/reference/generated/numpy.argwhere.html) exists. Why would you use `argmax()`? – Pranav Hosangadi Mar 02 '21 at 21:12

1 Answers1

1

You can check if there is a zero.

condition = a2 == 0
index = condition.argmax() if condition.any() else None

I think it's better to use np.where() in this case because it can be achieved with only one pass over the array, while both .argmax() and .any() will have to go through it again.

index = np.where(a2 == 0)[0]      # will be empty if none are found
index = index[0] if index else None
Reti43
  • 9,656
  • 3
  • 28
  • 44