Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

I have a sparse 2D matrix, typically something like this:

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

I'm interested in all nonzero elements in "test"

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

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

For each row I would like to print out all the nonzero elements, but skipping all rows containing only zero elements.

I would appreciate hints for this.

Thanks for the hints. This solved the 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]])

>>> for 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
like image 988
user2659801 Avatar asked Dec 24 '22 17:12

user2659801


2 Answers

Given

rows, cols = np.nonzero(test)

you could also 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.])
like image 115
unutbu Avatar answered Dec 29 '22 00:12

unutbu


Use array indexing:

test[test != 0]

There is no array operation to do this per-row (instead of for the entire matrix), as that would return a variable number of elements per row. You can use something like

[row[row != 0] for row in test]

to achieve that.

like image 27
valhallasw Avatar answered Dec 29 '22 00:12

valhallasw