I am trying to get a tuple that contains the indicies of the minimum value in an numpy array.
import numpy as np
a=np.array(([2,3,1],[5,4,6],[8,7,9]))
b=np.where(a==np.min(a))
print(b)
gives:
(array([0]),array([2]))
Attempting to map the result to a tuple:
c=map(tuple,b)
print(c)
gives:
[(0,), (2,)]
but what I want is:
(0,2)
Any suggestions other than np.where are perfectly acceptable. Thanks.
The easiest way to get your desired result is
>>> np.unravel_index(a.argmin(), a.shape)
(0, 2)
The argmin() method finds the index of the minimum element in the flattened array in a single pass, and thus is more efficient than first finding the minimum and then using a linear search to find the index of the minimum.
As the second step, np.unravel_index() converts the scalar index into the flattened array back into an index tuple. Note that the entries of the index tuple have the type np.int64 rather than plain int.
For a case when you would have multiple elements with the same min value, you might want to have a list of tuples. For such a case, you could use map after column-stacking the rows and columns info obtained from np.where, like so -
map(tuple,np.column_stack(np.where(a==np.min(a))))
Sample run -
In [67]: a
Out[67]:
array([[2, 2, 0, 1, 0],
[0, 2, 0, 0, 3],
[1, 0, 1, 2, 1],
[0, 3, 3, 3, 3]])
In [68]: map(tuple,np.column_stack(np.where(a==np.min(a))))
Out[68]: [(0, 2), (0, 4), (1, 0), (1, 2), (1, 3), (2, 1), (3, 0)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With