3

I have 2 large arrays with the exact same ammount of elements.

Array1=[[1,2,3][1,1,2]]
Array2=[[0,2,0][3,1,3]]

if Element in Array1="1", Replace "1" with whatever is in the same place as Array2

Output=[[0,2,3][3,1,2]]

Should be easy, but this late on a friday has my brains scrambled.

2 Answers 2

3
import numpy as np

Array1 = np.array([[1,2,3], [1,1,2]])
Array2 = np.array([[0,2,0], [3,1,3]])

b = np.where(Array1 == 1)

Array1[b] = Array2[b]

Result:

>>> Array1
array([[0, 2, 3],
       [3, 1, 2]])

As jorgeca pointed out the above solution can be reduced to:

b = Array1 == 1
Array1[b] = Array2[b]
Sign up to request clarification or add additional context in comments.

1 Comment

You could forgo the call to np.where (since Array1 == 1 returns a boolean mask that's already an index) or maybe use its three arguments' form.
2

This one's based on Akaval's solution, but in one line. It takes advantage of other features of np.where():

import numpy as np
Array1 = np.array([[1,2,3], [1,1,2]])  
Array2 = np.array([[0,2,0], [3,1,3]])

Output = np.where(Array1 == 1, Array2, Array1)

2 Comments

Nice, I did not know about this one-line solution. I guess the difference is that this creates a new array instead of modifying Array1.
@Akavall: I'd actually never heard about np.where() until your answer sent me to the documentation. This is actually pretty close to one of the examples on that page.

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.