Printing all non-zero elements in a 2D matrix in Python

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

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

      

I am interested in all non-zero items in the "test"

index = numpy.nonzero(test)

returns a tuple of arrays giving me the indices for non-null elements:

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

      

For each line, I would like to print all non-null elements, but skip all lines containing only null elements.

I would appreciate it.

Thanks for the tips. 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

      

+3


source to share


2 answers


Considering

rows, cols = np.nonzero(test)

      

you can also use so called extended 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])

      

gives

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

      

+4


source


Use array indexing:

test[test != 0]

      

There is no array operation for this row (not the entire matrix), as this returns a variable number of elements in the row. You can use something like



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

      

to achieve this.

+2


source







All Articles