mrsquid
mrsquid

Reputation: 635

Python Numpy Determine array index which contains overall max/min value

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.

Upvotes: 1

Views: 164

Answers (1)

Zaraki Kenpachi
Zaraki Kenpachi

Reputation: 5730

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]))

Upvotes: 2

Related Questions