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]])
我想在数组的每一行中找到最小值。我怎样才能做到这一点?
预期答案:
[[0.07704314 0. 0. 0. ]
[0. 0.02914078 0. 0. ]
[0.32757561 0 0. 0. ]
[0. 0. 0.26657932 0. ]]
解决方案
你可以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)
推荐阅读
- azure - Web API 使用 Microsoft Graph API 管理不同的租户
- c++ - Round-Robin Iterator 和 STL 的按值传递策略
- flutter - 如何在 Flutter 中复制 Android 应用程序表?
- .net - AWS DotNetCore Lambda - 一个解决方案中的多个项目
- azure - 如何控制/减少 Azure 服务总线中的吞吐量
- remote-access - Xbox 在开发模式下不允许远程访问
- git - 通过 WSL 克隆 GitHub 存储库失败
- r - 在 Rmarkdown 到 pdf 的预览中的方程式编号?
- kubernetes - 如何在 nginx 入口中的子路径上公开哨兵?
- php - 如果基本 url 包含端口号,则不会加载资产 - codeigniter 4