Home > Software engineering >  Replace multidimensional array with different array on condition (Python3.x)
Replace multidimensional array with different array on condition (Python3.x)

Time:10-26

I have three multidimensional arrays in Python 3.9 where I would like to replace the values of one array by the values of the second on condition of a third. So:

Array1 = [[[4, 2, 3], [1, 0, 10], [7, 4, 6]],
          [[8, 7, 95], [3, 5, 22], [0, 7, 0]],
          [[5, 0, 60], [5, 230, 70], [6, 76, 30]]]
Array2 = [[[12, 3, 4], [4, 55, 0], [0, 5, 76]],
          [[34, 60, 76], [40, 430, 0], [4, 0, 11]],
          [[2, 34, 0], [1, 0, 0], [76, 4, 77]]]
Mask = [[[0, 1, 0], [1, 0, 0], [1, 0, 0]],
        [[0, 1, 0], [0, 1, 1], [1, 1, 1]],
        [[1, 0, 1], [1, 0, 0], [1, 1, 0]]]

I would like to replace the values in the first array by the values of the second array, if at the same location in the mask array, the value is 1. So the result should be:

Array1 = array([[[  4,   3,   3],
                 [  4,   0,  10],
                 [  0,   4,   6]],

                [[  8,  60,  95],
                 [  3, 430,   0],
                 [  4,   0,  11]],

                [[  2,   0,   0],
                 [  1, 230,  70],
                 [ 76,   4,  30]]])

Is there any way to do is with a quick (numpy) command that doesn't require me to loop over the whole array? In practice the whole array has a size of (1500,2500,4), so that would take quite some processing.

Tnx in advance

CodePudding user response:

np.where does just the thing:

np.where(Mask, Array2, Array1)

Output:

array([[[  4,   3,   3],
        [  4,   0,  10],
        [  0,   4,   6]],

       [[  8,  60,  95],
        [  3, 430,   0],
        [  4,   0,  11]],

       [[  2,   0,   0],
        [  1, 230,  70],
        [ 76,   4,  30]]])
  • Related