1

I have two numpy arrays:

d1 = np.array([[1, 2, 1], [4, 3, 4], [4, 9, 0]])
d2 = np.array([[1, 0, 1], [0, 0, 0], [1, 0, 0]])

I would like to select values in d1 where the value of d2 is equal to 1 and based on condition, change the selected value in d1.

For instance, I want to select values of d1 where d2 is 1, see if they are less than 3, and if they were less than 3, replace them with 10. So, the result would be:

np.array([[10, 2, 10], [4, 3, 4], [4, 9, 0]])

I know how to use loop but I am interested in indexing solution if possible.

1 Answer 1

1

You could use np.where here chaining both conditions with a bitwise AND:

np.where((d1<3)&(d2==1), 10, d1)

array([[10,  2, 10],
       [ 4,  3,  4],
       [ 4,  9,  0]])
Sign up to request clarification or add additional context in comments.

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.