首页 > 解决方案 > 如何在使用 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]])

我想在数组的每一行中找到最小值。我怎样才能做到这一点?

预期答案:

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

标签: pythonnumpy

解决方案


你可以np.where这样使用:

np.where(a.argmin(1)[:,None]==np.arange(a.shape[1]), a, 0)

或者(更多行但可能更有效):

out = np.zeros_like(a)
idx = a.argmin(1)[:, None]
np.put_along_axis(out, idx, np.take_along_axis(a, idx, 1), 1)

推荐阅读