0

Suppose I have two arrays

array1=np.array([1,2,3,4,5,6,7,8,9,10])
array2=np.array([11,1,2,4,10,60,0,3,20,33])

I want to compare the two arrays and store the values that are bigger. I want to write a code that will check the first element of array1 with the first element of array2 and store the greatest value between them in a new array and so on.

I tried it with this code

array3=[]
i=0
while i<=len(array1):
    if array1[i]>array2[i]:
        array3.append(i)

However, the code doesn't give any output and keeps on running. The two array in question that i want to work with are very big so will a normal loop method work for big arrays as well?

5 Answers 5

2

If you're using numpy, using numpy all the way is preferable. It will be faster, and use less memory, than the iterative approach (and is more readable, too).

np.max([array1, array2], axis=0)

Your loop is infinite because your i never changes. If you fix that (either by adding i += 1 or by using for i in range(0, len(array1)):), you will only be appending elements where array1 one is larger, and leaving out any pairs where they are equal, or where the array2 one is larger: an else: would be needed.

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

Comments

2

You're probably looking for something like numpy.maximum:

import numpy as np

array1 = np.array([ 1, 2, 3, 4,  5,  6, 7, 8, 9,  10])
array2 = np.array([11, 1, 2, 4, 10, 60, 0, 3, 20, 33])

np.maximum(array1, array2)
# array([11,  2,  3,  4, 10, 60,  7,  8, 20, 33])

1 Comment

Huh, np.maximum. Learn something new every day.
1

A couple of things:

First, the reason it keeps going is that you are not incrementing your iterator i.

Second, currently you are adding the index of the greater number, and not the greater number. Try the following code(pure python):

array3 = []
i = 0
while i < len(array1):
    if array1[i] > array2[i]:
        array3.append(array1[i])
    else:
        array3.append(array2[i])
    i += 1

Comments

0

This should work!

import numpy as np

array1=np.array([1,2,3,4,5,6,7,8,9,10])
array2=np.array([11,1,2,4,10,60,0,3,20,33])

array3=[]
i=0
while i<len(array1):
    if array1[i]>array2[i]:
        array3.append(array1[i])
    else:
        array3.append(array2[i])
    i += 1

print(array3)

enter image description here

Comments

0

Wanted to do this with a list comprehension. This would work assuming the arrays are always the same size.

[max([array1[i],array2[i]]) for i in range(len(array1))]

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.