How to conditionally merge two numpy arrays of the same shape

It sounds simple, and I think it is too complicated.

I want to create an array whose elements are created from two source arrays of the same shape, depending on which element is larger in the source arrays.

to illustrate:

import numpy as np array1 = np.array((2,3,0)) array2 = np.array((1,5,0)) array3 = (insert magic) >> array([2, 5, 0)) 

I cannot decide how to create an array 3 that combines the elements of array1 and array2 to create an array where only the larger of the two values โ€‹โ€‹of the element array1 / array2 is accepted.

Any help would be greatly appreciated. Thanks.

+7
python arrays numpy
source share
2 answers

We could use NumPy's built-in np.maximum , made just for this purpose -

 np.maximum(array1, array2) 

Another way would be to use NumPy ufunc np.max in the 2D stack and max-reduce along the first axis (axis=0) -

 np.max([array1,array2],axis=0) 

Timing for 1 million datasets -

 In [271]: array1 = np.random.randint(0,9,(1000000)) In [272]: array2 = np.random.randint(0,9,(1000000)) In [274]: %timeit np.maximum(array1, array2) 1000 loops, best of 3: 1.25 ms per loop In [275]: %timeit np.max([array1, array2],axis=0) 100 loops, best of 3: 3.31 ms per loop # @Eric Duminil soln1 In [276]: %timeit np.where( array1 > array2, array1, array2) 100 loops, best of 3: 5.15 ms per loop # @Eric Duminil soln2 In [277]: magic = lambda x,y : np.where(x > y , x, y) In [278]: %timeit magic(array1, array2) 100 loops, best of 3: 5.13 ms per loop 
+18
source share

If your condition ever gets more complicated, you can use np.where :

 import numpy as np array1 = np.array((2,3,0)) array2 = np.array((1,5,0)) array3 = np.where( array1 > array2, array1, array2) # array([2, 5, 0]) 

You can replace array1 > array2 with any condition. If all you need is maximum, go with @Divakar answer.

And just for fun:

 magic = lambda x,y : np.where(x > y , x, y) magic(array1, array2) # array([2, 5, 0]) 
+12
source share

All Articles