简体   繁体   中英

Mask for an array in the same shape

Array2[:,0] contains array1 row indexes, array2[:,1] contains array1 element value. I want to get mask same shape as array1 in vectorized way.

array1=
[[0 1 2]
 [3 4 5]
 [6 7 8]]

array2=
[[0 1]
 [1 3]
 [1 5]
 [2 7]
 [2 9]]

Code:

array1 = np.arange(9).reshape(-1,3)
array2 = np.arange(10).reshape(-1,2)
array2[:,0]=[0,1,1,2,2]

print(array1[array2[:, 0]] == array2[:, 1,None])

Result I get:

[[False  True False]
 [ True False False]
 [False False  True]
 [False  True False]
 [False False False]]

The result I want to get:

[[False  True False]
 [ True False  True]
 [False  True False]

Edit: The loop solution looks like this:

mask=np.zeros_like(array1)
for (y,x) in array2:
    mask[y,(np.where(array1[y,:] == x))] = True

You can perform a mapping back:

array1 = np.arange(9).reshape(-1,3)
array2 = np.arange(10).reshape(-1,2)
array2[:,0] = [0,1,1,2,2]

xs, ys = array1[array2[:, 0]] == array2[:, 1,None]

mask = np.zeros_like(array1, dtype=bool)
mask[, ys] = True

This gives us for the given sample data:

>>> mask
array([[False,  True, False],
       [ True, False,  True],
       [False,  True, False]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM