python - 如何获取二维 numpy 数组中每一行的前 2 个值的索引,但不包括特定区域?
问题描述
例如,我有一个二维数组:
p = np.array([[21,2,3,1,12,13],
[4,5,6,14,15,16],
[7,8,9,17,18,19]])
b = np.argpartition(p, np.argmin(p, axis=1))[:, -2:]
com = np.ones([3,6],dtype=np.int)
com[np.arange(com.shape[0])[:,None],b] = 0
print(com)
b 是 p 中每一行的前 2 个值的索引:
b = [[0 5]
[4 5]
[4 5]]
com 是 np.ones 矩阵,大小与 p 相同,索引与 b 相同的元素将变为 0。所以结果是:
com = [[0 1 1 1 1 0]
[1 1 1 1 0 0]
[1 1 1 1 0 0]]
现在我还有一个约束:
p[0:2,0:2]
不应考虑这些区域中的数字,因此结果应为:
b = [[4 5]
[4 5]
[4 5]]
我怎样才能做到这一点 ?提前致谢!
解决方案
确保你的问题很清楚。不确定我是否理解您的限制。这是一个例子:
# the data
p = np.array([[21, 2, 3, 1, 12, 13],
[4, 5, 6, 14, 15, 16],
[7, 8, 9, 17, 18, 19]])
# not sure if this is what you mean by constraint
# but lets ignore values in first two cols and rows
p[0:2, 0:2] = 0
# return the idx of highest values
b = np.argpartition(p, -2)[:, -2:]
推荐阅读
- javascript - 如何在转换原点和滚动条之间切换
- javascript - 使用点击处理程序更改函数内部的全局范围变量
- r - 在ggplot2中,当有facet_wrap时,如何让所有geom_col bar的值相同时颜色相同?
- php - 为什么我的 PHP 代码在将数据添加到 MySQL db 时返回这些类型的错误?
- r - 查找并用 nomatch 替换批量
- r - 将一个变量中的级别名称添加到另一个变量中的级别名称
- java - Java:在运行时导入
- java - EclipseLink:未加载实体
- r - 情节未出现在预渲染的 Shiny 中
- ethereum - 如何计算最优gas limit和gas price?