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

Issue

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

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])

Answered By – I'mahdi

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *