0

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

2
  • are all three lists always the same length? Commented Oct 25, 2021 at 16:42
  • Yes they are of exact same length. Marked Answer has solved my problems. Thanks though. Commented Oct 25, 2021 at 18:02

1 Answer 1

3

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]]])
Sign up to request clarification or add additional context in comments.

1 Comment

This works great. I was unaware that the numpy.where function could handle a masking array like an array of booleans. Thankyou!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.