How to return all the minimum indices in numpy

I am a little bit confused reading the documentation of argmin function in numpy. It looks like it should do the job:

Reading this

Return the indices of the minimum values along an axis.

I might assume that

np.argmin([5, 3, 2, 1, 1, 1, 6, 1])

will return an array of all indices: which will be [3, 4, 5, 7]

But instead of this it returns only 3. Where is the catch, or what should I do to get my result?


Solution 1:

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

Solution 2:

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