44

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?

3 Answers 3

67

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.

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

3 Comments

I would try to hold the data in a two-dimensional array right from the start, and then use the second option.
@SvenMarnach The axis argument calls reduce in the end, I don't understand why it matters.
Note that unlike np.maximum, np.maximum.reduce won't work out of the box with masked array. Neither is np.ma.maximum.reduce(…, axis=0) . You can manually keep track of the masks however.
21

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.

Comments

1

You can also use:

np.column_stack([A, B, C]).max(axis=1)

The result is the same as the solutions from the other answers.

I use Pandas more heavily than NumPy so for me it's easier to think of 1D arrays as something similar to Pandas Series. The above would be equivalent to:

pd.concat([A, B, C], axis=1).max(axis=1)

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.