Haden96
Haden96

Reputation: 47

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

Upvotes: 0

Views: 187

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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 = np.where(array1[array2[:, 0]] == array2[:, 1,None])

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

This gives us for the given sample data:

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

Upvotes: 2

Related Questions