0

I'm trying to compare two lists and replace the values of the first one by the values of the second one only if they are smaller.

I tried the smaller than function from python but this seems to replace the whole list.

A = [7 , 10 , 2, 5 , 9]
B = [8 , 12 , 1, 4 , 7]

A[A < B] = B

This replaces list A by list B, probably because it compares the whole list. I would want only the values replaced that are smaller than the ones in B resulting in:

[8 , 12 , 2 , 5 , 9]

4
  • Are you sure that A[A<B] = B doesn't just assign B to A[1]? Commented Oct 24, 2019 at 15:06
  • What does this have to do with numpy? If you're using numpy, please show a proper example. Commented Oct 24, 2019 at 15:06
  • Yes, it completely replaces A. About the numpy that was a mistake, sorry. Commented Oct 24, 2019 at 15:12
  • I've added a non numpy solution if you want to avoid the import Commented Oct 24, 2019 at 15:25

3 Answers 3

4

Do:

import numpy as np

A = np.array([7, 10, 2, 5, 9])
B = np.array([8, 12, 1, 4, 7])

A[A < B] = B[A < B]
print(A)

Output

[ 8 12  2  5  9]
Sign up to request clarification or add additional context in comments.

3 Comments

This looks like the right answer. However, when I try this the firs number of A stays a 7.
@Michiel I cannot reproduce, I ran this on my computer and gives the same output as in the answer. What numpy version are you using?
I am using 1.13.3. Found my mistake, I forgot to add np.array. Thanks for the help!
2

With numpy.place - to change elements of an array in-place based on conditional:

import numpy as np

a = np.array([7 , 10 , 2, 5 , 9])
b = np.array([8 , 12 , 1, 4 , 7])
np.place(a, a < b, b)
print(a)    # [ 8 12  2  5  9]

Comments

1

If you want to keep this in vanilla python, you can do something like:

A[:] = [max(a, b) for a, b in zip(A, B)]

This does a true in-place operation, such that id(A) does not change. A simpler approach might be to just reassign A:

A = [max(a, b) for a, b in zip(A, B)]

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.