Python 如何在使用numpy保持数组维度不变的情况下在每行中找到最小值?

Python 如何在使用numpy保持数组维度不变的情况下在每行中找到最小值?,python,numpy,Python,Numpy,我有以下数组: np.array([[0.07704314, 0.46752589, 0.39533099, 0.35752864], [0.45813299, 0.02914078, 0.65307364, 0.58732429], [0.32757561, 0.32946822, 0.59821108, 0.45585825], [0.49054429, 0.68553148, 0.26657932, 0.38495586]])

我有以下数组:

np.array([[0.07704314, 0.46752589, 0.39533099, 0.35752864],
          [0.45813299, 0.02914078, 0.65307364, 0.58732429],
          [0.32757561, 0.32946822, 0.59821108, 0.45585825],
          [0.49054429, 0.68553148, 0.26657932, 0.38495586]])
我想在数组的每一行中找到最小值。我怎样才能做到这一点

预期答复:

[[0.07704314 0.         0.         0.        ]
 [0.         0.02914078 0.         0.        ]
 [0.32757561 0          0.         0.        ]
 [0.         0.         0.26657932 0.        ]]

np.amin(a,axis=1)
其中a是你的np数组

IIUC首先找出每行的
min
值,然后我们根据最小值将原始数组中的所有最小值屏蔽为真,使用
多个
(矩阵),得到我们需要的结果

np.multiply(a,a==np.min(a,1)[:,None])
Out[225]: 
array([[0.07704314, 0.        , 0.        , 0.        ],
       [0.        , 0.02914078, 0.        , 0.        ],
       [0.32757561, 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.26657932, 0.        ]])

您可以使用
np。其中
如下所示:

np.where(a.argmin(1)[:,None]==np.arange(a.shape[1]), a, 0)
或(更多线路,但可能更高效):


我想保持维度和索引。我想在值不是最小值的地方填充0。您的解决方案给出了最小值的一维数组。是的,您是对的。由于某种原因,我没有阅读预期答案部分。对不起,您可以在这里使用
keepdims=True
kwarg。
out = np.zeros_like(a)
idx = a.argmin(1)[:, None]
np.put_along_axis(out, idx, np.take_along_axis(a, idx, 1), 1)