I want to find the indices[i,j] of the maximum value in a 2d numpy array:
a = numpy.array([[1,2,3],[4,3,1]])
I tried to do it using numpy.argsort() but it returns an array because it can be done along an axis only. One solution can be by comparing elements at all indices (along both axes) returned by argsort using for loops, but it seems kind of complicated for this. Maybe there is a simple solution?
You want np.unravel_index
. The np.argmax
will return an index as if the flattened version of array is traversed. The unravel_index
will give you the N-D
indices.
a = np.random.randint(0, 10, (4,4))
ind = np.unravel_index(np.argmax(a, axis=None), a.shape) # returns a tuple
Maybe this can return what you are looking for? It returns the index of the max (
max_xy = np.where(a == a.max() )
Zip the result to get the index as list of tuples:
zip(max_xy[0], max_xy[1]) #=> [(1, 0)]
In case of more than one max: a = np.array([[4,2,3],[4,3,4]])
, it returns #=> [(0, 0), (1, 0), (1, 2)]
To return as a tuple the first maximum found, just fetch the first element of the array:
zip(max_xy[0], max_xy[1])[0] #=> (0, 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