1

How to use one array filter out another array with non-zero value?

from numpy import array

a = array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])

b = array([[0, 0, 1, 0, 0],
           [0, 0, 2, 0, 0],
           [0, 0, 3, 0, 0],
           [0, 0, 4, 0, 0],
           [0, 0, 5, 0, 0]])

Expected result:

array([[ 0, 0, 2,  0, 0],
       [ 0, 0, 7,  0, 0],
       [ 0, 0, 12, 0, 0],
       [ 0, 0, 17, 0, 0],
       [ 0, 0, 22, 0, 0]])

Thank you

2 Answers 2

1

The easiest way if you want a new array would be np.where with 3 arguments:

>>> import numpy as np
>>> np.where(b, a, 0)
array([[ 0,  0,  2,  0,  0],
       [ 0,  0,  7,  0,  0],
       [ 0,  0, 12,  0,  0],
       [ 0,  0, 17,  0,  0],
       [ 0,  0, 22,  0,  0]])

If you want to change a in-place you could instead use boolean indexing based on b:

>>> a[b == 0] = 0
>>> a
array([[ 0,  0,  2,  0,  0],
       [ 0,  0,  7,  0,  0],
       [ 0,  0, 12,  0,  0],
       [ 0,  0, 17,  0,  0],
       [ 0,  0, 22,  0,  0]])
Sign up to request clarification or add additional context in comments.

Comments

1

One line solution:

a * (b != 0)

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.