0

I have two numpy arrays A and B and a mask mask of booleans (True/False), all of identical dimensions. I want to replace the elements in A with those of B where the corresponding element of mask is True; where the corresponding element of mask is False I want to retain the original element of A. How can I do this?

Example:

# Input
A = np.arange(9).reshape(3,3)
B = A*10
mask = np.array([[True, True, False], [False, True, False], [False, False, True]])

# Output
desired_output = np.array([[0, 10, 2], [3, 40, 5], [6, 7, 80]])

2 Answers 2

3

Simply:

In [54]: A[mask]=B[mask]
In [55]: A
Out[55]: 
array([[ 0, 10,  2],
       [ 3, 40,  5],
       [ 6,  7, 80]])

np.putmask(A,mask,B) also works.

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

Comments

0

Try map

def repl(a,b,m):
    return b if m else a

desired_output = list(map(repl,A,B,mask))

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.