Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform one-dimensional Numpy array into mask suitable for array index update of 2-dimensional array [duplicate]

Tags:

python

numpy

Given a 2-dimensional array a, I want to update select indices specified by b to a fixed value of 1.

test data:

import numpy as np

a = np.array(
    [[0, 1, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 1, 0],
    [1, 0, 0, 0],
    [0, 1, 0, 1],
    [0, 0, 0, 0]]
)

b = np.array([1, 2, 2, 0, 3, 3])

One solution is to transform b into a masked array like this:

array([[0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 1, 0],
       [1, 0, 0, 0],
       [0, 0, 0, 1],
       [0, 0, 0, 1]])

which would allow me to do a[b.astype(bool)] = 1 and solve the problem.

How can I transform b into the "mask" version below?

like image 458
AlexG Avatar asked Jun 24 '26 21:06

AlexG


1 Answers

No need to build the mask, use indexing directly:

a[np.arange(len(b)), b] = 1

Output:

array([[0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 1, 0],
       [1, 0, 0, 0],
       [0, 1, 0, 1],
       [0, 0, 0, 1]])

That said, the mask could be built using:

mask = b[:,None] == np.arange(a.shape[1])

Output:

array([[False,  True, False, False],
       [False, False,  True, False],
       [False, False,  True, False],
       [ True, False, False, False],
       [False, False, False,  True],
       [False, False, False,  True]])
like image 89
mozway Avatar answered Jun 26 '26 11:06

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!