Sunday, November 7, 2021

ItsMyCode: numpy.argmax() in Python

ItsMyCode |

The numpy.argmax() function returns the indices of the maximum values along an axis. In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence will be returned.

Syntax

numpy.argmax(a, axis=None, out=None)

Parameters

  • array: Input array
  • axis [int, optional]By default, the index is into the flattened array, otherwise along the specified axis.
  • out [array optional]: If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

Return Value

An array of indices into the array. It will have the same shape as the array.shape with the dimension along the axis removed.

Finding the maximum element from a matrix with Python numpy.argmax()

import numpy as np
a = np.arange(6).reshape(2,3) + 10
print(a)

print("The maxiumm count in an array is ", np.argmax(a))

Output

[[10 11 12]
 [13 14 15]]
The maxiumm count in an array is  5

The output returned by the numpy.argmax() is 5. Since we have not passed any axis to the argmax function, it returns the index of the last element in the array.  

In simple terms, if you don’t specify the axis to Python’s numpy.argmax() it will return the count of an array.

Using np.unravel_index on argmax output

We can use the np.unravel_index function for getting an index corresponding to a 2D array from the numpy.argmax output.

import numpy as np
a = np.arange(6).reshape(2,3) + 10
print(a)

index = np.unravel_index(np.argmax(a), a.shape)
print(index)
print(a[index])

Output

[[10 11 12]
 [13 14 15]]
(1, 2)
15

Finding Maximum Elements along columns using Python numpy.argmax()

The below code returns the index value of the maximum elements along each column.

import numpy as np
a = np.arange(12).reshape(4,3) + 10
print(a)

print("Max elements", np.argmax(a, axis=0))

Output

[[10 11 12]
 [13 14 15]
 [16 17 18]
 [19 20 21]]
Max elements [3 3 3]

The post numpy.argmax() in Python appeared first on ItsMyCode.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...