12

I want to combine two numpy arrays to produce an array with the largest values from each array.

import numpy as np

a  = np.array([[ 0.,  0.,  0.5],
               [ 0.1,  0.5,  0.5],
               [ 0.1,  0.,  0.]])

b  = np.array([[ 0.,  0.,  0.0],
               [ 0.5,  0.1,  0.5],
               [ 0.5,  0.1,  0.]])

I would like to produce

array([[ 0.,  0.,  0.5],
       [ 0.5,  0.5,  0.5],
       [ 0.5,  0.1,  0.]])

I know you can do

a += b

which results in

array([[ 0. ,  0. ,  0.5],
       [ 0.6,  0.6,  1. ],
       [ 0.6,  0.1,  0. ]])

This is clearly not what I'm after. It seems like such an easy problem and I assume it most probably is.

3 Answers 3

10

You can use np.maximum to compute the element-wise maximum of the two arrays:

>>> np.maximum(a, b)
array([[ 0. ,  0. ,  0.5],
       [ 0.5,  0.5,  0.5],
       [ 0.5,  0.1,  0. ]])

This works with any two arrays, as long as they're the same shape or one can be broadcast to the shape of the other.

To modify the array a in-place, you can redirect the output of np.maximum back to a:

np.maximum(a, b, out=a)

There is also np.minimum for calculating the element-wise minimum of two arrays.

Sign up to request clarification or add additional context in comments.

Comments

6

You are looking for the element-wise maximum.

Example:

>>> np.maximum([2, 3, 4], [1, 5, 2])
array([2, 5, 4])

http://docs.scipy.org/doc/numpy/reference/generated/numpy.maximum.html

Comments

3
inds =  b > a
a[inds] = b[inds]

This modifies the original array a which is what += is doing in your example which may or may not be what you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.