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

How to assign a value to certain indices of a Numpy array when the indices are given in another numpy array?

I am new to Python and even more so to NumPy and I couldnt find a solution for this for now.
I have a Numpy array a = [1 4 6] and another b that consists of 3 rows and 3 cols full of zeros

[[0 0 0]
 [0 0 0]
 [0 0 0]]

How can I assign a certain value v to exactly the 3 indexes of a of b
My idea would be something like this

for x in range(a):
        b[x] = v

which doesn’t work. I also tried it with converting a to a list() beforehand

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

>Solution :

Assuming you want to assign a value v=1 in the nth indices of the flatten array b, you could use:

a = np.array([1, 4, 6])
b = np.zeros((3, 3))

b.flat[a] = 1

Or use numpy.unravel_index:

b[np.unravel_index(a, b.shape)] = 1

Output:

array([[0., 1., 0.],
       [0., 1., 0.],
       [1., 0., 0.]])
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