首页 > 解决方案 > 如何获取二维 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]]

我怎样才能做到这一点 ?提前致谢!

标签: pythonarraysnumpy

解决方案


确保你的问题很清楚。不确定我是否理解您的限制。这是一个例子:

# 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:]

推荐阅读