numpy - Print all the non-zero element in a 2D matrix in Python -


i have sparse 2d matrix, typically this:

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

i'm interested in nonzero elements in "test"

index = numpy.nonzero(test) returns tuple of arrays giving me indices nonzero elements:

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

for each row print out nonzero elements, skipping rows containing 0 elements.

i appreciate hints this.

thanks hints. solved problem:

>>> test array([[ 1.,  0.,  0.,  0.], [ 0.,  0.,  0.,  0.], [ 0.,  2.,  1.,  0.], [ 0.,  0.,  0.,  1.]])  >>> transp=np.transpose(np.nonzero(test)) >>> transp array([[0, 0],    [2, 1],    [2, 2],    [3, 3]])  >>> index in range(len(transp)): row,col = transp[index] print 'row index ',row,'col index ',col,' value : ', test[row,col] 

giving me:

  row index  0 col index  0  value :  1.0   row index  2 col index  1  value :  2.0   row index  2 col index  2  value :  1.0   row index  3 col index  3  value :  1.0 

given

rows, cols = np.nonzero(test) 

you use so-called advanced integer indexing:

test[rows, cols] 

for example,

test = np.array([[ 1.,  0.,  0.,  0.],        [ 0.,  0.,  0.,  0.],        [ 0.,  2.,  1.,  0.],        [ 0.,  0.,  0.,  1.]])  rows, cols = np.nonzero(test)  print(test[rows, cols]) 

yields

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

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -