Skip to main content
Documents
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy argmax()

NumPy's `argmax()` function is used in array computation and analysis to find the index of the maximum value within an array. This function is particularly useful for identifying the position of the highest element in a dataset.

Usage

The `argmax()` function is used when you need to determine the index of the maximum element along a specific axis of an array. It is helpful in scenarios where the position of the maximum value is more relevant than the value itself.

numpy.argmax(a, axis=None)

In this syntax, `a` is the input array, and `axis` specifies the axis along which to find the maximum value. If `axis` is `None`, the function will consider the flattened array. Note that if the input array is empty, it raises a `ValueError`.

Examples

1. Basic Example

import numpy as np

a = np.array([1, 3, 7, 0, 5, 7])
index = np.argmax(a)
print(index)

This example returns `2`, which is the index of the first occurrence of the maximum value `7` in the array.

2. Multidimensional Array

import numpy as np

a = np.array([[5, 12, 3], [2, 8, 7]])
index = np.argmax(a, axis=0)
print(index)

In this example, `argmax()` returns `[0, 0, 1]`, indicating the indices of the maximum values along each column.

3. Using `argmax()` with Axis

import numpy as np

a = np.array([[4, 9, 2], [1, 6, 7]])
index = np.argmax(a, axis=1)
print(index)

Here, `argmax()` returns `[1, 2]`, showing the indices of the maximum values along each row.

Tips and Best Practices

  • Understand your data shape. Ensure you know the shape of your array and what axis you want to apply the `argmax()` function to for meaningful results.
  • Handle ties carefully. `argmax()` returns the first occurrence of the maximum value, which is vital when duplicate maximum values exist.
  • Combine with other functions. Use `argmax()` in conjunction with other NumPy functions like `max()` to validate results and gain further insights.
  • Consider performance. For large datasets, be mindful of performance, especially if flattening the array with `axis=None`.
  • Masked Arrays. `argmax()` can be used with masked arrays, which is useful when dealing with datasets that contain missing values.
  • Data Types. `argmax()` handles various data types such as floats and complex numbers effectively, returning the index of the maximum value according to the data type's ordering rules.