Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

numpy array mask with range of elements specified by another array row-wise

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading