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

Time:03-19

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

g[tuple([range(len(min_)), min_])]

Output:

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