Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise array maximum function in NumPy (more than two arrays)

Tags:

python

max

numpy

I'm trying to return maximum values of multiple array in an element-wise comparison. For example:

A = array([0, 1, 2]) B = array([1, 0, 3]) C = array([3, 0, 4]) 

I want the resulting array to be array([3,1,4]).

I wanted to use numpy.maximum, but it is only good for two arrays. Is there a simple function for more than two arrays?

like image 869
Wang Yuan Avatar asked Feb 16 '14 20:02

Wang Yuan


People also ask

Can numpy arrays have more than 2 dimensions?

Creating arrays with more than one dimensionIn general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.

What is the way to find the maximum number in the numpy array?

Here, we create a single-dimensional NumPy array of integers. Now try to find the maximum element. To do this we have to use numpy. max(“array name”) function.

How do you find the max of two arrays in Python?

maximum() function is used to find the element-wise maximum of array elements. It compares two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned.

Which function is used to add two numpy arrays element-wise?

add() function is used when we want to compute the addition of two array. It add arguments element-wise. If shape of two arrays are not same, that is arr1.


2 Answers

With this setup:

>>> A = np.array([0,1,2]) >>> B = np.array([1,0,3]) >>> C = np.array([3,0,4]) 

You can either do:

>>> np.maximum.reduce([A,B,C]) array([3, 1, 4]) 

Or:

>>> np.vstack([A,B,C]).max(axis=0) array([3, 1, 4]) 

I would go with the first option.

like image 51
Daniel Avatar answered Oct 08 '22 03:10

Daniel


You can use reduce. It repeatedly applies a binary function to a list of values...

For A, B and C given in question...

np.maximum.reduce([A,B,C])   array([3,1,4]) 

It first computes the np.maximum of A and B and then computes the np.maximum of (np.maximum of A and B) and C.

like image 39
Gurmeet Singh Avatar answered Oct 08 '22 02:10

Gurmeet Singh