How to find index of max value in Numpy?

Let’s learn how to find the index of the maximum value in a NumPy array using the argmax function. This is a common operation in data analysis when you need to locate the position of the highest value within an array.

Numpy index of max value

How to use numpy index of max?

You may need to find the index of the max value in the Numpy array. The argmax function can be used to find the index of the maximum value in a Numpy array.

See also  How to create empty array in Numpy?

The numpy.argmax function scans the entire array and returns the index of the first occurrence of the maximum value. It’s useful when you need to know the position of the maximum value, not just the value itself.

import numpy as np

my_list = np.array([5, 7, 8, 3, 2, 8])
print(f"This is my array: \n {my_list}")

max_value = my_list.argmax()
print(f"Index of max value: \n {max_value}")

As you may see, there are two occurrences of 8, but argmax returned the index of the first one.

See also  How to you find the cumulative sum in Python?

Handling Multi-Dimensional Arrays

If you’re working with multi-dimensional arrays, you can specify the axis along which to find the maximum value’s index using the axis parameter.

import numpy as np

my_2d_array = np.array([[5, 7, 8],
                        [3, 2, 8]])
print(f"This is my 2D array:\n{my_2d_array}")

max_indices_axis0 = np.argmax(my_2d_array, axis=0)
print(f"Indices of maximum values along axis 0: {max_indices_axis0}")

max_indices_axis1 = np.argmax(my_2d_array, axis=1)
print(f"Indices of maximum values along axis 1: {max_indices_axis1}")

The maximum values in each column are found, and their row indices are returned. For this array, the maximum values in each column are in row 0.

See also  Solving "ImportError: No module named 'numpy'"

The maximum values in each row are found, and their column indices are returned. For both rows, the maximum value 8 is at column index 2.