Assign values to different index positions in Numpy array
You can use tuple indexing:
>>> import numpy as np
>>> a = np.zeros((4,2))
>>> vals = [4,3,2,1]
>>> pos = [(0,0),(1,1),(2,0),(3,1)]
>>> rows, cols = zip(*pos)
>>> a[rows, cols] = vals
>>> a
array([[ 4., 0.],
[ 0., 3.],
[ 2., 0.],
[ 0., 1.]])
Here is a streamlined version of @wim's answer based on @hpaulj's comment. np.transpose
automatically converts the Python list of tuples into a NumPy array and transposes it. tuple
casts the index coordinates to tuples which works because a[rows, cols]
is equivalent to a[(rows, cols)]
in NumPy.
import numpy as np
a = np.zeros((4, 2))
vals = range(4)
indices = [(0, 0), (1, 1), (2, 0), (3, 1)]
a[tuple(np.transpose(indices))] = vals
print(a)