Home > Back-end >  Merge two NumPy arrays into one
Merge two NumPy arrays into one

Time:06-11

Say I have the following two arrays, a and b:

import numpy as np

a = np.array([[[1, 0],
             [1, 1]],

            [[1, 0],
             [0, 0]],

            [[0, 0],
             [1, 0]]])

b = np.array([[[0, 2],
             [0, 0]],

            [[0, 0],
             [0, 2]],

            [[0, 2],
             [0, 2]]])

and I wish to 'overlap' them so that I get the following result:

          [[[1, 2],
            [1, 1]],

           [[1, 0],
            [0, 2]],

           [[0, 2],
            [1, 2]]]

In the case there is an overlapping co-ordinate, I would just take 1. How could I achieve this?

CodePudding user response:

Using a simple sum I manage to get the desired result:

import numpy as np

a = np.array([[[1, 0],
             [1, 1]],

            [[1, 0],
             [0, 0]],

            [[0, 0],
             [1, 0]]])

b = np.array([[[0, 2],
             [0, 0]],

            [[0, 0],
             [0, 2]],

            [[0, 2],
             [0, 2]]])

print(a b)

Output:

[[[1 2]
  [1 1]]

 [[1 0]
  [0 2]]

 [[0 2]
  [1 2]]]

CodePudding user response:

Maybe you can try by starting with a matrix with zeros and then assign the flags one by one:

import numpy as np
a = np.array([[[1, 0],
               [1, 1]],
              [[1, 0],
               [0, 0]],
              [[0, 0],
               [1, 0]]])
b = np.array([[[0, 2],
               [0, 0]],
              [[0, 0],
               [0, 2]],
              [[0, 2],
               [0, 2]]])
# Create a matrix with zeros
c = np.zeros(a.shape, dtype='int')
# Assign flags
c[b==2] = 2
c[a==1] = 1 # Put in second because priority to 1 in case of overlapping
# Output
print(c)

Output:

array([[[1, 2],
        [1, 1]],

       [[1, 0],
        [0, 2]],

       [[0, 2],
        [1, 2]]])
  • Related