numpy 2d阵列操作,保持一定的位置

时间:2014-07-24 17:28:57

标签: python numpy 2d where

我有两个2d numpy数组:

X2d = np.array([[0,4,5,0],
                [7,8,4,3],
                [0,0,9,8]])

Y2d = np.array([[1,0,4,8],
                [0,3,8,5],
                [0,6,0,8]])

#and I would like to get these two:

X2dresult = np.array([[0,0,5,0],
                      [0,8,4,3],
                      [0,0,0,8]])

Y2dresult = np.array([[0,0,4,0],
                      [0,3,8,5],
                      [0,0,0,8]])

所以基本上我需要保持两个矩阵都大于0的位置。我可以使用numpy.where函数或类似的东西来获得这些结果吗? 感谢

2 个答案:

答案 0 :(得分:2)

您可以使用按位AND或OR和numpy.where

>>> X2d = np.array([[0,4,5,0],
...                 [7,8,4,3],
...                 [0,0,9,8]])
>>> 
>>> Y2d = np.array([[1,0,4,8],
...                 [0,3,8,5],
...                 [0,6,0,8]])
>>> indices = np.where(~((X2d > 0) & (Y2d > 0)))
>>> X2d[indices] = 0
>>> Y2d[indices] = 0
>>> X2d
array([[0, 0, 5, 0],
       [0, 8, 4, 3],
       [0, 0, 0, 8]])
>>> Y2d
array([[0, 0, 4, 0],
       [0, 3, 8, 5],
       [0, 0, 0, 8]])

我认为按位OR更好更清晰:

>>> X2d = np.array([[0,4,5,0],
...                 [7,8,4,3],
...                 [0,0,9,8]])
>>> 
>>> Y2d = np.array([[1,0,4,8],
...                 [0,3,8,5],
...                 [0,6,0,8]])
>>> indices = np.where((X2d == 0) | (Y2d == 0))
>>> X2d[indices] = 0
>>> Y2d[indices] = 0
>>> X2d
array([[0, 0, 5, 0],
       [0, 8, 4, 3],
       [0, 0, 0, 8]])
>>> Y2d
array([[0, 0, 4, 0],
       [0, 3, 8, 5],
       [0, 0, 0, 8]])

答案 1 :(得分:0)

X2dresult = ((X2d > 0) & (Y2d > 0)) * X2d
Y2dresult = ((X2d > 0) & (Y2d > 0)) * Y2d

允许Z = ((X2d > 0) & (Y2d > 0)),然后Z[i,j] = True当且仅当X2d[i,j] > 0Y2d[i,j] > 0

现在X2dresult = Z * X2d,所以X2dresult[i,j] = Z[i,j] * X2d[i,j]Z[i,j] = False为0,X2d[i,j]Z[i,j] = True。 (因为int(True) = 1int(False) = 0

因此,在X2dresult数组中,0X2d具有Y2d的所有元素都是0