1

Say I have a Numpy nd array like below.

arr = np.array([[2, 3, 9], [1,6,7], [4, 5, 8]])

The numpy array is a 3 x 3 matrix.

What I want to do is the find row index which contains the overall maximum value.

For instance in the above example, the maximum value for the whole ndarray is 9. Since it is located in the first row, I want to return index 0.

What would be the most optimal way to do this?

I know that

np.argmax(arr)

Can return the index of the maximum for the whole array, per row, or per column. However is there method that can return the index of the row which contains the overall maximum value?

It would also be nice if this could also be changed to column wise easily or find the minimum, etc.

I am unsure on how to go about this without using a loop and finding the overall max while keeping a variable for the index, however I feel that this is inefficient for numpy and that there must be a better method.

Any help or thoughts are appreciated.

Thank you for reading.

1 Answer 1

2

Use where with amax, amin.

import numpy as np

arr = np.array([[2, 3, 9], [1,6,7], [4, 5, 8]])

max_value_index = np.where(arr == np.amax(arr))
min_value_index = np.where(arr == np.amin(arr))

Output:

(array([0]), array([2]))
(array([1]), array([0]))
Sign up to request clarification or add additional context in comments.

2 Comments

Dang didn't know Kenpachi was also a python master, does your python skill increase too when you take off the eyepatch? Also thanks for the help!
@mrsquid after that my skill is quadruplet ^^

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.