Get maximum value of each index between multiple numpy arrays

Viewed 870

So I have three NumPy arrays, all with 300 elements in them. Is there any way I could create a new array with the greatest value at each index? I'm not sure where to start since I'm not comparing numbers in the same list. I know there is some kind of loop where you start from 0 to the length and you need to initialize an empty array to populate, but I'm not sure how'd you compare the values at each index. Very likely I'm overthinking.

Ex.
a = [16,24,52]
b = [22,15,136]
c = [9,2,142]
Output = [22,24,142]
3 Answers

Since all your arrays have the same lenghts, you can stack them vertically by using np.vstack. Then, use np.max on axis=0:

import numpy as np

a = np.array([16, 24, 52])
b = np.array([22, 15, 136])
c = np.array([9, 2, 142])

out = np.max(np.vstack((a, b, c)), axis=0)
print(out)

Output:

[ 22  24 142]

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
----------------------------------------

You can use amax.

np.amax(np.array([a,b,c]), axis=0)

Output:

array([ 22,  24, 142])

If you want to follow your original idea involving a loop and the initialization of an array, you can use np.zeros() followed by range() and max():

import numpy as np

a = np.array([16, 24, 52])
b = np.array([22, 15, 136])
c = np.array([9, 2, 142])

# initialize array filled with zeros
Output = np.zeros(len(a), dtype=int)

# populate array
for i in range(len(a)):
    Output[i] = max(a[i], b[i], c[i])

print(Output)

Output:

[ 22  24 142]
Related