I have an nxd numpy array of zeros. For every row in this array, I am tasked with converting a specified column to be a 1. To this end, I have been given a list of size n such that the ith value of this list is the index to be turned into a 1.
This task can be accomplished via a for loop as below:
import numpy as np
N=5; D =3
array = np.zeros(shape=(N,D))
ones_index = [0,2,1,0,1]
for row, column in enumerate(ones_index):
array[row,column] = 1
While this works just fine, I imagine that numpy has some function to achieve this above much more cleanly. Does there exist a numpy function that converts a list of indices into a certain values in an array?
>Solution :
One possible solution:
array = np.zeros(shape=(N, D))
ones_index = [0, 2, 1, 0, 1]
array[np.arange(N), ones_index] = 1
print(array)
Prints:
[[1. 0. 0.]
[0. 0. 1.]
[0. 1. 0.]
[1. 0. 0.]
[0. 1. 0.]]