Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a matrix from a matrix of indices

I want to fill a matrix from an array of indices :

import numpy as np

indx = [[0,1,2],[1,2,4],[0,1,3],[2,3,4],[0,3,4]]
x = np.zeros((5,5))
for i in range(5):
    x[i,indx[i]] = 1.

The result is :

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

As desired.

Question

Is there a way to do this in pure python/numpy without looping ?

like image 736
Toool Avatar asked Jul 14 '17 17:07

Toool


1 Answers

Use advanced-indexing after intialization -

x[np.arange(len(indx))[:,None], indx] = 1
like image 81
Divakar Avatar answered Oct 24 '22 17:10

Divakar