Warm tip: This article is reproduced from stackoverflow.com, please click
arrays max numpy python min

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

发布于 2020-04-09 22:55:34

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.

Questioner
mrsquid
Viewed
17
Zaraki Kenpachi 2020-02-01 16:54

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