2

I have two 2d numpy arrays:

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]])

So basically I need to keep those positions where both of the matrices are greater than 0. Can I use numpy.where function or something like that to get these results? Thanks

Qfwfq
  • 185
  • 1
  • 7

2 Answers2

2

You can use bitwise AND or OR and numpy.where for this:

>>> 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]])

I think bitwise OR is better and clearer to read:

>>> 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]])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0
X2dresult = ((X2d > 0) & (Y2d > 0)) * X2d
Y2dresult = ((X2d > 0) & (Y2d > 0)) * Y2d

Let Z = ((X2d > 0) & (Y2d > 0)), Then Z[i,j] = True if and only if X2d[i,j] > 0 and Y2d[i,j] > 0

Now X2dresult = Z * X2d, So X2dresult[i,j] = Z[i,j] * X2d[i,j], which is 0 if Z[i,j] = False and X2d[i,j] if Z[i,j] = True. (because int(True) = 1 and int(False) = 0)

So, in X2dresult array all elements are 0 in those position where either X2d or Y2d has 0.

Corei13
  • 401
  • 2
  • 9