How to get the index of a maximum element in a NumPy array along one axis How to get the index of a maximum element in a NumPy array along one axis numpy numpy

How to get the index of a maximum element in a NumPy array along one axis


>>> a.argmax(axis=0)array([1, 1, 0])


>>> import numpy as np>>> a = np.array([[1,2,3],[4,3,1]])>>> i,j = np.unravel_index(a.argmax(), a.shape)>>> a[i,j]4


argmax() will only return the first occurrence for each row.http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

If you ever need to do this for a shaped array, this works better than unravel:

import numpy as npa = np.array([[1,2,3], [4,3,1]])  # Can be of any shapeindices = np.where(a == a.max())

You can also change your conditions:

indices = np.where(a >= 1.5)

The above gives you results in the form that you asked for. Alternatively, you can convert to a list of x,y coordinates by:

x_y_coords =  zip(indices[0], indices[1])