Argmin (and argmax)

Contents

Argmin (and argmax)#

We sometimes want to know where a value is in an array.

import numpy as np

By “where” we mean, the position (index) of an element that contains a particular value.

In particular, we often find we want to know the position (index) of the minimum or maximum values in an array. Enter … argmin and argmax.

Argmin, argmax#

Here is an array:

arr = np.array([2, 99, -1, 4, 99])
arr
array([ 2, 99, -1,  4, 99])

We can get the minimum value with Numpy min:

np.min(arr)
-1

Sometimes we want to know the position (index) of the minimum value. Numpy argmin returns the position of the minimum value:

min_pos = np.argmin(arr)
min_pos
2

Therefore, we can get the minimum value again with:

arr[min_pos]
-1

There is a matching argmax function that returns the position of the maximum value:

np.max(arr)
99
max_pos = np.argmax(arr)
max_pos
1
arr[max_pos]
99

Notice that there are two values of 99 in this array, and therefore, two maximum values. np.argmax returns the index of the first maximum values. np.argmin does the same, if there is more than one minimum value.