我有两个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函数或类似的东西来获得这些结果吗? 感谢
答案 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] > 0
和Y2d[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) = 1
和int(False) = 0
)
因此,在X2dresult
数组中,0
或X2d
具有Y2d
的所有元素都是0
。