fill numpy array with specific values

124 Views Asked by At

I have a 5x5 array with zeros. import numpy as np

x = np.zeros((5,5)):

[[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]

I want to fill 1's at certain positions:

input=[(2,2),(1,1),(3,4)] :
     [[0. 0. 0. 1. 0.]
     [0. 0. 0. 0. 0.]
     [0. 0. 1. 0. 0.]
     [0. 1. 0. 0. 0.]
     [0. 0. 0. 0. 0.]] 

how do I do that given input?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use use itemset

[x.itemset(t, 1) for t in input]

in tuple you set the locacation and last argument is the value to set

0
On
x = np.zeros((5,5))
for pair in input:
    x[pair[0]][pair[1]]=1

code is self explanatory.