akilat90 akilat90 - 2 months ago 9
Python Question

Using a numpy array to assign values to another array

I have the following numpy array

matrix
,

matrix = np.zeros((3,5), dtype = int)

array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])


Suppose I have this numpy array
indices
as well

indices = np.array([[1,3], [2,4], [0,4]])

array([[1, 3],
[2, 4],
[0, 4]])


Question: How can I assign
1
s to the elements in the
matrix
where their indices are specified by the
indices
array. A vectorized implementation is expected.

For more clarity, the output should look like:

array([[0, 1, 0, 1, 0], #[1,3] elements are changed
[0, 0, 1, 0, 1], #[2,4] elements are changed
[1, 0, 0, 0, 1]]) #[0,4] elements are changed

Answer

Here's one approach using NumPy's fancy-indexing -

matrix[np.arange(matrix.shape[0])[:,None],indices] = 1