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

For each row of a numpy array, set specific elements to n

I have a 2d array arr. Here’s an example:

>> arr
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

I also have a 2d array of indices indices (with indices.shape[0] == arr.shape[0], and indices.shape[1] <= arr.shape[1]). Here is an example:

>>> indices
array([[0, 1],
       [1, 2],
       [0, 2],
       [0, 2]])

Now, I want to set some elements of arr to -1. Specifically, on the first row of arr, the first and the second element should be set to -1 (because indices[0] == [0, 1]). On the second row of arr, the second and the third element should be set to -1 (because indices[1] == [1, 2]). And so on.

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

This would be the expected result:

array([[ -1, -1,  2],
       [  3, -1, -1],
       [ -1,  7, -1],
       [ -1, 10, -1]])

I tried to look for existing solutions but I haven’t found any. Any suggestion?

>Solution :

Broadcast assignment:

>>> arr[np.arange(4)[:, None], indices] = -1
>>> arr
array([[-1, -1,  2],
       [ 3, -1, -1],
       [-1,  7, -1],
       [-1, 10, -1]])
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