2

I would like to get all indexes of maximum values for each row from ndarray. For example, i have

arr = np.array([[1, 3, 3], [1, 5, 4]])

And i would like to get indexes of all 3's from first row, and all 5's from second row.

np.where(((arr == arr[0].max()) | (arr == arr[1].max())))

And it returns

(array([0, 0, 1], dtype=int64), array([1, 2, 1], dtype=int64))

I want something like that but more universal for any amount of rows. Because np.where(arr == arr.argmax()) doesn't work like i want it to work. It only returns indexes of first maxium that it met in each row.

1
  • 2
    (arr==arr.max(axis=1,keepdims=True)).nonzero()? Commented Oct 10, 2020 at 1:43

1 Answer 1

1

@Paul's answer in comments might be the best you can find. Writing it for readers. arr.max(1) find max in each row and arr==arr.max(1,keepdims=True) finds all elements in each row that are equal to corresponding max in that row. Finally nonzero returns indices of those elements:

(arr==arr.max(axis=1,keepdims=True)).nonzero()

output for OP's example:

(array([0, 0, 1]), array([1, 2, 1]))
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.