In many cases, where the size of the array is too large, it takes too much time to find the maximum elements from them. For this purpose, the numpy module of Python provides a function called numpy.argmax(). This function returns indices of the maximum values are returned along with the specified axis.
numpy.argmax(a, axis=None, out=None)
x: array_like
This parameter defines the source array whose maximum value we want to know.
axis: int(optional)
This parameter defines the axis along which the index is present, and by default, it is into the flattened array.
out: array(optional)
This parameter defines the ndarray in which the result is going to be inserted. This will be of the same type and shape, which is appropriate for storing the result
This parameter defines a ndarray, which contains the indices of the array. The shape is the same as x.shape with the dimension along the axis removed.
Import numpy as np x = np.arange(20).reshape(4,5) + 7 x y=np.argmax(a) y
Output:
In the above code
In the output, it shows the indices of the maximum element in the array.
Import numpy as np x = np.arange(20).reshape(4,5) + 7 y=np.argmax(x, axis=0) z=np.argmax(x, axis=1) y z
Output:
Import numpy as np x = np.arange(20).reshape(4,5) + 7 indices = np.unravel_index(np.argmax(x, axis=None), x.shape) indices x[indices]
Output:
import numpy as np a = np.array([[5,2,1], [3,7,9],[0, 4, 6]]) index_arr = np.argmax(a, axis=-1) index_arr # Same as np.max(a, axis=-1, keepdims=True) result = np.take_along_axis(a, np.expand_dims(index_arr, axis=-1), axis=-1) result1 # Same as np.max(a, axis=-1) result = np.take_along_axis(a, np.expand_dims(index_arr, axis=-1), axis=-1).squeeze(axis=-1) result2
Output:
In the above code
In the output, it shows indices of the maximum elements in the array and the values which are present on that indices.