Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge three numpy arrays, keep largest value

Tags:

python

numpy

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?

like image 392
sfluck Avatar asked Dec 18 '22 14:12

sfluck


1 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]])
like image 160
Naga kiran Avatar answered Jan 01 '23 01:01

Naga kiran