Merge two NumPy arrays into one

Issue

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?

Solution

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

Answered By – Cesar Lopes

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published