Search code examples
pythonmatrix-indexing

Python indirect indexing


This might be a super easy question if you know how to do it, but I just can't figure out the syntax:

I have an array of 5x10 zeros: y1 = np.zeros((5,10)) and an array 5x1 of index: index=np.array([2,3,2,5,6]). For each row of y1, I would like to set 1 at the column given by the index. The result would look like

array([[ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.]])

Anyone can help please :-) ?


Solution

  • You can do multi-dimensional array indexing with array[index_1, index_2]. For your problem:

    y1[range(y1.shape[0]), index] = 1
    

    range(y1.shape[0]) generates the array [0,1,...,n-1], where n is the number of rows in y1. This array is your row index, and index is your column index.