简体   繁体   中英

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

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

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.])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM