通过像np.in1d这样的索引数组为2D阵列屏蔽2D Numpy数组

时间:2015-03-17 16:33:39

标签: python numpy

    np.array(
[[0,13,0,2,0,0,0,0,0,0,0,0],
 [0,0,15,0,9,0,0,0,0,0,0,0],
 [0,0,0,0,0,18,0,0,0,0,0,0],
 [0,0,0,0,27,0,20,0,0,0,0,0],
 [0,0,0,0,0,20,0,10,0,0,0,0],
 [0,0,0,0,0,0,0,0,8,0,0,0],
 [0,0,0,0,0,0,0,14,0,14,0,0],
 [0,0,0,0,0,0,0,0,12,0,25,0],
 [0,0,0,0,0,0,0,0,0,0,0,11],
 [0,0,0,0,0,0,0,0,0,0,15,0],
 [0,0,0,0,0,0,0,0,0,0,0,7],
 [0,0,0,0,0,0,0,0,0,0,0,0]])

我试图找到如何采取像上面那样的numpy数组,然后在一个高性能操作掩码中使用我想要归零的元素索引

[0,1] [1,4] [4,7] [7,8] [8,11]

所以我剩下的就是

np.array(
[[0,0,0,2,0,0,0,0,0,0,0,0],
 [0,0,15,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,18,0,0,0,0,0,0],
 [0,0,0,0,27,0,20,0,0,0,0,0],
 [0,0,0,0,0,20,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,8,0,0,0],
 [0,0,0,0,0,0,0,14,0,14,0,0],
 [0,0,0,0,0,0,0,0,0,0,25,0],
 [0,0,0,0,0,0,0,0,0,0,0,0],
 [0,0,0,0,0,0,0,0,0,0,15,0],
 [0,0,0,0,0,0,0,0,0,0,0,7],
 [0,0,0,0,0,0,0,0,0,0,0,0]])

类似于np.in1d的功能但是对于2D阵列?我可以迭代每个元素,但数组可以真正大量,因此矢量单个操作掩码将是最好的。可能吗?如果这是一个愚蠢的问题,我相信我会被告知!

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式直接访问这些索引

indexes = [[0,1], [1,4], [4,7], [7,8], [8,11]]
indexes =zip(*indexes)
>>[(0, 1, 4, 7, 8), (1, 4, 7, 8, 11)]
a[indexes[0], indexes[1]]=0
>>
[[ 0  0  0  2  0  0  0  0  0  0  0  0]
 [ 0  0 15  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0 18  0  0  0  0  0  0]
 [ 0  0  0  0 27  0 20  0  0  0  0  0]
 [ 0  0  0  0  0 20  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  8  0  0  0]
 [ 0  0  0  0  0  0  0 14  0 14  0  0]
 [ 0  0  0  0  0  0  0  0  0  0 25  0]
 [ 0  0  0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0  0  0  0  0  0  0 15  0]
 [ 0  0  0  0  0  0  0  0  0  0  0  7]
 [ 0  0  0  0  0  0  0  0  0  0  0  0]]

答案 1 :(得分:1)

我认为你在寻找这个

a = np.array(
[[0,13,0,2,0,0,0,0,0,0,0,0],
 [0,0,15,0,9,0,0,0,0,0,0,0],
 [0,0,0,0,0,18,0,0,0,0,0,0],
 [0,0,0,0,27,0,20,0,0,0,0,0],
 [0,0,0,0,0,20,0,10,0,0,0,0],
 [0,0,0,0,0,0,0,0,8,0,0,0],
 [0,0,0,0,0,0,0,14,0,14,0,0],
 [0,0,0,0,0,0,0,0,12,0,25,0],
 [0,0,0,0,0,0,0,0,0,0,0,11],
 [0,0,0,0,0,0,0,0,0,0,15,0],
 [0,0,0,0,0,0,0,0,0,0,0,7],
 [0,0,0,0,0,0,0,0,0,0,0,0]])

b = np.array([[0,1],[1,4],[4,7],[7,8],[8,11]])

# get x coordinates in an array
c1 = b[:,0]
# get y coordinates in an array
c2 = b[:,1]
a[c1[:,None],c2] = 0

a 
array([[ 0,  0,  0,  2,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0, 15,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0, 18,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0, 27,  0, 20,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0, 20,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  8,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0, 14,  0, 14,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 25,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 15,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  7],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0]])