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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With