python - 如何使用 numpy 找到每行的最小元素的 n 个索引?
问题描述
例如:
n = 2
p1 = np.asarray([[20, 30, 10],
[10, 20, 30],
[30, 20, 10]])
结果,我想要:
[ [0, 0, 2],
[1, 0, 1],
[2, 1, 2] ]
每行的第一个数字就是 p1 中的行号。剩余的 n 个数字是该行的最小元素的索引。所以:
[0, 0, 2]
# 0 is the index of the first row in p1.
# (0, 2 are the indices of minimum elements of the row)
[1, 0, 1]
# 1 is the index of the second row in p1.
# (0, 1 are the indices of minimum elements of the row)
[2, 1, 2]
# 2 is the index of the third row in p1.
# (1, 2 are the indices of minimum elements of the row)
非常感谢!!!
解决方案
用于np.argpartition
查找前两个最小值:
import numpy as np
n = 2
p1 = np.asarray([[20, 30, 10],
[10, 20, 30],
[30, 20, 10]])
pos = np.argpartition(p1, axis=1, kth=2)
res = np.hstack([np.arange(3)[:, None], np.sort(pos[:, :2])])
print(res)
输出
[[0 0 2]
[1 0 1]
[2 1 2]]
一旦找到np.hstack
用于连接行索引的最小值并与之相连。
推荐阅读
- typescript - 在一个类型中引用一个键两次
- javascript - 将两个 snap svg 组组合成一个组
- sql - SQL to pandas JOIN w/AND 问题
- php - 将 json 数组转换为 php 数组
- visual-studio - HoloLens 错误:“出现部署错误。继续吗?”
- python - 如何在python中打印S3键名
- javascript - 如何使用vue显示分钟和秒?
- ruby - 如何细化如何选择哈希键?
- haskell - 在 Haskell 中调试/可视化递归函数调用的最简单方法是什么?
- android - 加载新数据时,recyclerview 顶部的项目布局突然发生变化