'how do I properly use the result of argmin to slice out an array of the minimums?

I'm looking to slice out the minimum value along the first axis of an array. For example, in the code below, I want to print out np.array([13, 0, 12, 3]). However, the slicing isn't behaving as I would think it does.
(I do need the argmin array later and don't want to just use np.min(g, axis=1))

import numpy as np
g = np.array([[13, 23, 14], [12, 23, 0], [39, 12, 92], [19, 4, 3]])
min_ = np.argmin(g, axis=1)
print(g[:, min_])

What is happening here? Why is my result from the code

[[13 14 23 14]
 [12  0 23  0]
 [39 92 12 92]
 [19  3  4  3]]

Other details:
Python 3.10.2
Numpy 1.22.1



Solution 1:[1]

If you want use np.argmin, you can try this:

For more explanation : from min_ you have array([0, 2, 1, 2]) but for accessing to array you need ((0, 1, 2, 3), (0, 2, 1, 2)) for this reason you can use range.

min_ = np.argmin(g, axis=1)
g[range(len(min_)), min_] # like as np.min(g ,axis=1)

Output:

array([13,  0, 12,  3])

Solution 2:[2]

Your code is printing the first, third, second, and third columns of the g array, in that order.

>>> np.argmin(g, axis=1)
array([0, 2, 1, 2])  # first, third, second, third

If you want to get the minimum value of each row, use np.min:

>>> np.min(g, axis=1)
array([13,  0, 12,  3])

Solution 3:[3]

When you write g[:, min_], you're saying: "give me all of the rows (shorthand :) for columns at indices min_ (namely 0, 2, 1, 2)".

What you wanted to say was: "give me the values at these rows and these columns" - in other words, you're missing the corresponding row indices to match the column indices in min_.

Since your desired row indices are simply a range of numbers from 0 to g.shape[0] - 1, you could technically write it as:

print(g[range(g.shape[0]), min_])
# output: [13  0 12  3]

But @richardec's solution is better overall if your goal is to extract the row-wise min value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 richardec
Solution 3 jfaccioni