How to return all the minimum indices in numpy

I would like to quickly add that as user grofte mentioned, np.where returns a tuple and it states that it is a shorthand for nonzero which has a corresponding method flatnonzero which returns an array directly.

So, the cleanest version seems to be

my_list = np.array([5, 3, 2, 1, 1, 1, 6, 1])
np.flatnonzero(my_list == my_list.min())
=> array([3, 4, 5, 7])

See the documentation for numpy.argmax (which is referred to by the docs for numpy.argmin):

In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.

The phrasing of the documentation ("indices" instead of "index") refers to the multidimensional case when axis is provided.

So, you can't do it with np.argmin. Instead, this will work:

np.where(arr == arr.min())

That documentation makes more sense when you think about multidimensional arrays.

>>> x = numpy.array([[0, 1],
...                  [3, 2]])
>>> x.argmin(axis=0)
array([0, 0])
>>> x.argmin(axis=1)
array([0, 1])

With an axis specified, argmin takes one-dimensional subarrays along the given axis and returns the first index of each subarray's minimum value. It doesn't return all indices of a single minimum value.

To get all indices of the minimum value, you could do

numpy.where(x == x.min())

Tags:

Python

Numpy