Having a 2d numpy array, for example
data = np.ones((3, 5))
how can i create an boolean mask for this array for all elements of a row up to a specific index stored row-wise in another np.array. So the "end index" array looks like
np.array([0, 2, 3])
The output should look like:
[[True False False False False]
[True True True False False]
[True True True True False]]
I tried fancy indexing with a row and column array, but dont know how to specify the column ranges for each row.
>Solution :
You don’t really need the array of ones, you just need the second dimension (5, which can be inferred from the shape of data), then perform broadcasting with arange and your mask:
N = 5
# or N = data.shape[1]
mask = np.array([0, 2, 3])
np.arange(N) <= mask[:, None]
Output:
array([[ True, False, False, False, False],
[ True, True, True, False, False],
[ True, True, True, True, False]])