2

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]
1
  • 1
    What does this have to do with multiplication? Commented Mar 9, 2020 at 5:37

3 Answers 3

1

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
----------------------------------------
Sign up to request clarification or add additional context in comments.

Comments

1

You can use amax.

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

Output:

array([ 22,  24, 142])

Comments

1

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]

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.