[파이썬][numpy] numpy `argmax`와 `argmin`

In data science and machine learning projects, we often encounter scenarios where we need to find the index of the maximum or minimum value in an array. This is where the argmax and argmin functions in the numpy library come in handy.

numpy argmax

The argmax function returns the index of the maximum value in an array along a specified axis.

Here’s an example to demonstrate the usage of argmax:

import numpy as np

# Creating a 1-dimensional array
arr = np.array([4, 8, 5, 2, 7])

# Finding the index of the maximum value
max_index = np.argmax(arr)

print("Array:", arr)
print("Max Value Index:", max_index)
print("Max Value:", arr[max_index])

Output:

Array: [4 8 5 2 7]
Max Value Index: 1
Max Value: 8

In this example, we create a 1-dimensional numpy array called arr with five elements. The argmax function returns the index 1, which corresponds to the second element of the array (8). We can then access the maximum value using arr[max_index].

numpy argmin

Similar to argmax, the argmin function returns the index of the minimum value in an array along a specified axis.

Let’s look at an example:

import numpy as np

# Creating a 2-dimensional array
arr = np.array([[3, 6, 1], [2, 9, 8]])

# Finding the index of the minimum value
min_index = np.argmin(arr)

print("Array:\n", arr)
print("Min Value Index:", min_index)
print("Min Value:", arr.flatten()[min_index])

Output:

Array:
 [[3 6 1]
 [2 9 8]]
Min Value Index: 2
Min Value: 1

In this example, we create a 2-dimensional numpy array called arr with two rows and three columns. The argmin function returns the index 2, which corresponds to the third element of the flattened array (1). We can then access the minimum value using arr.flatten()[min_index].

Conclusion

The numpy functions argmax and argmin are useful tools when we need to find the index of the maximum and minimum values in an array. They provide a convenient and efficient way to perform these operations in Python.