Zian Lai Zian Lai - 3 years ago 173
Python Question

Use one array to filter out another array

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

Answer Source

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]])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download