np.argmax
is a NumPy function that returns the indices of the maximum values along a specified axis in an array. If the input array is multi-dimensional, you can specify the axis along which the maximum values are computed.
Here’s a simple example:
import numpy as np
arr = np.array([1, 5, 2, 8, 3])
# Get the index of the maximum value in the array
index_of_max_value = np.argmax(arr)
print("Array:", arr)
print("Index of Maximum Value:", index_of_max_value)
print("Maximum Value:", arr[index_of_max_value])
Output:
Array: [1 5 2 8 3]
Index of Maximum Value: 3
Maximum Value: 8
In this example, np.argmax(arr)
returns the index (position) of the maximum value in the array arr
. The maximum value is 8, and it is at index 3 (0-indexed).
You can also use np.argmax
with multi-dimensional arrays and specify the axis along which the maximum values should be computed. For example:
import numpy as np
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Get the indices of the maximum values along each column (axis=0)
indices_of_max_values = np.argmax(arr_2d, axis=0)
print("2D Array:")
print(arr_2d)
print("Indices of Maximum Values along Each Column:", indices_of_max_values)
Output:
2D Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Indices of Maximum Values along Each Column: [2 2 2]
In this 2D array example, np.argmax(arr_2d, axis=0)
returns the indices of the maximum values along each column (axis=0). The result is an array [2, 2, 2]
, indicating that the maximum values in each column are found in the third row.