0

Given a numpy array of shape (2, 4):

input = np.array([[False, True, False, True], [False, False, True, True]])

I want to return an array of shape (N,) where each element of the array is the index of the first True value:

expected = np.array([1, 2])

Is there an easy way to do this using numpy functions and without resorting to standard loops?

2
  • Try np.argmax Commented Feb 13, 2022 at 4:34
  • @hpaulj, what would the call to argmax look like in this case then using input? Commented Feb 13, 2022 at 4:48

2 Answers 2

1

np.max with axis finds the max along the dimension; argmax finds the first max index:

In [42]: arr = np.array([[False, True, False, True], [False, False, True, True]])
In [43]: np.argmax(arr, axis=1)
Out[43]: array([1, 2])
Sign up to request clarification or add additional context in comments.

Comments

0

This worked for me:

nonzeros = np.nonzero(input)
u, indices = np.unique(nonzeros[0], return_index=True)
expected = nonzeros[1][indices]

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.