positon of minima in numpy in python

To find the position of minima in a NumPy array in Python, you can use the numpy.argmin() function. This function returns the indices of the minimum values along an axis.

Here's an example:

main.py
import numpy as np

# Create a 1D array
arr = np.array([3, 2, 4, 1, 5])

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

print("Minimum value:", arr[min_index])
print("Index of minimum value:", min_index)
223 chars
11 lines

Output:

main.py
Minimum value: 1
Index of minimum value: 3
43 chars
3 lines

If you have a multi-dimensional array and want to find the position of the minimum value along a particular axis, you can pass the axis parameter to argmin(). Here's an example:

main.py
import numpy as np

# Create a 2D array
arr = np.array([[3, 2], [1, 4], [5, 0]])

# Find the index of the minimum value along axis 0
min_indices = np.argmin(arr, axis=0)

print("Minimum values along axis 0:", arr[min_indices, range(arr.shape[1])])
print("Indices of minimum values along axis 0:", min_indices)
310 chars
11 lines

Output:

main.py
Minimum values along axis 0: [1 0]
Indices of minimum values along axis 0: [1 2]
81 chars
3 lines

In this example, arr[min_indices, range(arr.shape[1])] is used to extract the actual minimum values along axis 0.

gistlibby LogSnag