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

24,732

Solution 1

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.

Solution 2

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.

Share:
24,732
Wang Yuan
Author by

Wang Yuan

I'm a water quality modeler. I'm currently modeling sediment water intraction.

Updated on May 15, 2021

Comments

  • Wang Yuan
    Wang Yuan almost 3 years

    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?

  • Sven Marnach
    Sven Marnach about 10 years
    I would try to hold the data in a two-dimensional array right from the start, and then use the second option.
  • Daniel
    Daniel about 10 years
    @SvenMarnach The axis argument calls reduce in the end, I don't understand why it matters.