Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two numpy arrays to form an array with the largest value from each array

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.

like image 284
Michael T Avatar asked Feb 26 '15 12:02

Michael T


People also ask

How do I combine multiple NumPy arrays into one?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.

Can you combine NumPy arrays?

NumPy's concatenate function can be used to concatenate two arrays either row-wise or column-wise. Concatenate function can take two or more arrays of the same shape and by default it concatenates row-wise i.e. axis=0.

Which method is used to join two NumPy arrays?

The concatenate() function is a function from the NumPy package. This function essentially combines NumPy arrays together. This function is basically used for joining two or more arrays of the same shape along a specified axis.

How do I append a NumPy array to another NumPy array?

You can append a NumPy array to another NumPy array by using the append() method. In this example, a NumPy array “a” is created and then another array called “b” is created. Then we used the append() method and passed the two arrays.


1 Answers

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.

like image 159
Alex Riley Avatar answered Oct 22 '22 04:10

Alex Riley