How to find index of max value in Numpy?

Learn how to use NumPy’s argmax() function to find the index position of the maximum value in arrays, essential for locating peaks and extreme values in data analysis.

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.

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 Get the Length of a NumPy Array

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  How to resolve MemoryError: Unable to allocate array in 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.

# Compare argmax with other max-finding methods
my_array = np.array([5, 7, 8, 3, 2, 8])

# Method 1: argmax - returns index
index = np.argmax(my_array)
print(f"argmax: {index}")  # 2

# Method 2: max - returns value
value = np.max(my_array)
print(f"max: {value}")  # 8

# Method 3: where - returns all indices where condition is true
indices = np.where(my_array == np.max(my_array))
print(f"where (all max indices): {indices}")  # (array([2, 5]),)

# Method 4: max and argmax together
max_value = my_array[np.argmax(my_array)]
max_index = np.argmax(my_array)
print(f"Max value: {max_value}, Index: {max_index}")