We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

However, you may sometimes want to find theindexat which the maximum value occurs.

numpy-argmax

Theargmax()function helps you find the index of the maximum in both one-dimensional and multidimensional arrays.

Lets proceed to learn how it works.

you’ve got the option to code along by starting a Python REPL or launching a Jupyter notebook.

numpy-argmax-2darray

First, lets import NumPy under the usual aliasnp.

In this case,np.max(array_1)returns 10, which is correct.

Suppose youd like to find the index at which the maximum value occurs in the array.

numpy-argmax-axis0

The first element is at index 0; the second element is at index 1, and so on.

Youll have to tap into the array and dive into the item at the first index.

We have usednp.where()withonlythe condition, but this isnotthe recommended method to use this function.

numpy-argmax-axis1

When we specify theaxisparameter in theargmax()function call, the array is reduced along that axis.

But setting thekeepdimsparameter toTrueensures that the returned output is of the same shape as the input array.

Using NumPy argmax() to Find the Index of the Maximum Element

#1.

Let us use the NumPy argmax() function to find the index of the maximum element inarray_1.

Theargmax()function returns 4, which is correct!

If we redefinearray_1such that 10 occurs twice, theargmax()function returnsonlythe index of the first occurrence.

For the rest of the examples, well use the elements ofarray_1we defined in example #1.

For a two-dimensional array, axis 0 denotes the rows and axis 1 denotes the columns.

Even though we calledargmax()on the two-dimensional array, it still returns 4.

This is identical to the output for the one-dimensional array,array_1from the previous section.

Why does this happen?

This is because we have not specified any value for the axis parameter.

This output can be a bit difficult to comprehend, but well understand how it works.

Lets visualize this for better understanding.

fire off the following code snippet and observe the output.

Can you parse the output?

We have setaxis = 1to compute the index of the maximum element along the columns.

Theargmax()function returns, for each row, the column number in which the maximum value occurs.

We see that the Python interpreter throws aTypeError, as theout_arrwas initialized to an array of floats by default.

As array indices are always integers, we should set thedtypeparameter tointwhen defining the output array.

The output of theargmax()function can now be accessed in the arrayout_arr.

Conclusion

I hope this tutorial helped you understand how to use the NumPy argmax() function.

you could initiate the code examples in a Jupyter notebook.

Lets review what weve learned.

Next, check out the in-depth guide on Python sets.

Also learn how to use the Python Sleep Function to add delays to your code.