-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?

2
  • Does this answer your question? Python: find position of element in array Commented Mar 2, 2021 at 21:10
  • Why does .find as suggested in the linked duplicate not work? In fact, if you want a numpy solution, np.argwhere() exists. Why would you use argmax()? Commented Mar 2, 2021 at 21:12

1 Answer 1

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

2 Comments

I actually like the first answer more! Thanks!
@kikatuso Why would you ever use argmax() for a janky, improvised argwhere()?

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.