Merge three numpy arrays, keep largest value

Viewed 677

I want to merge three numpy arrays, for example:

a = np.array([[0,0,1],[0,1,0],[1,0,0]])
b = np.array([[1,0,0],[0,1,0],[0,0,1]])
c = np.array([[0,1,0],[0,2,0],[0,1,0]])

a = array([[0, 0, 1],
           [0, 1, 0],
           [1, 0, 0]])

b = array([[1, 0, 0],
           [0, 1, 0],
           [0, 0, 1]])

c = array([[0, 1, 0],
           [0, 2, 0],
           [0, 1, 0]])

Desired result would be to overlay them but keep the largest value where multiple elements are not 0, like in the middle.

array([[1, 1, 1],
       [0, 2, 0],
       [1, 1, 1]])

I solved this by iterating over all elements with multiple if-conditions. Is there a more compact and more beautiful way to do this?

2 Answers

You can try of stacking arrays together in extra dimension with Numpy np.dstack method

and extract the maximum value specific to added dimension

# Stacking arrays together
d = np.dstack([a,b,c])
d.max(axis=2)

Out:

array([[1, 1, 1],
       [0, 2, 0],
       [1, 1, 1]])

NumPy's np.ufunc.reduce allows to apply a function cumulatively along a given axis. We can just concatenate the arrays and reduce with numpy.maximum to keep the accumulated elementwise maximum:

np.maximum.reduce([a,b,c])

array([[1, 1, 1],
       [0, 2, 0],
       [1, 1, 1]])
Related