Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all the minimum indices in numpy

Tags:

python

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?

like image 596
Salvador Dali Avatar asked Sep 02 '13 23:09

Salvador Dali


People also ask

What does argmin return?

Returns the indices of the minimum values along an axis. Input array. By default, the index is into the flattened array, otherwise along the specified axis.

How do you find min and max in NumPy?

numpy. amax() will find the max value in an array, and numpy. amin() does the same for the min value.


2 Answers

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()) 
like image 99
user2357112 supports Monica Avatar answered Sep 21 '22 16:09

user2357112 supports Monica


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()) 
like image 22
nneonneo Avatar answered Sep 23 '22 16:09

nneonneo