-3

I have two 2D arrays like:

A=array[[4,5,6],
        [0,7,8],
        [0,9,0]]

B = array[[11,12,13],
          [14,15,16],
          [17,18,19]]

In array A where element value is 0 i want to replace same value in array B by 0 and store the changed matrix in a new variable and retain the old B matrix.

Thanks in advance.

Akash Basudevan
  • 820
  • 5
  • 15
Nick
  • 1
  • 1

1 Answers1

5
import numpy as np
A=np.array([[4,5,6],
    [0,7,8],
    [0,9,0]])

B =np.array([[11,12,13],
      [14,15,16],
      [17,18,19]])
C = B.copy()
B[A == 0] = 0
C, B = B, C

The line B[A == 0] basically first gets all the the values where the array A is 0 by the line A == 0 . It return a boolean array with true at the position where value is zero in array A. This boolean array is then used to mask the array B and assigns 0 to indices the boolean values is True.

Akash Basudevan
  • 820
  • 5
  • 15