Home > Software engineering >  How to assign a value to certain indices of a Numpy array when the indices are given in another nump
How to assign a value to certain indices of a Numpy array when the indices are given in another nump

Time:01-22

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

CodePudding user response:

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.]])
  • Related