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

Question:

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

Asked By: Dave Twickenham

||

Answers:

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.]])
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.