Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Created September 26, 2018 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chelseatroy/50c7d02686c96d13eb4d53f3554c85f1 to your computer and use it in GitHub Desktop.
Save chelseatroy/50c7d02686c96d13eb4d53f3554c85f1 to your computer and use it in GitHub Desktop.
spmatrix nonzero implementation
def nonzero(self):
"""nonzero indices
Returns a tuple of arrays (row,col) containing the indices
of the non-zero elements of the matrix.
Examples
--------
>>> from scipy.sparse import csr_matrix
>>> A = csr_matrix([[1,2,0],[0,0,3],[4,0,5]])
>>> A.nonzero()
(array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))
"""
# convert to COOrdinate format
A = self.tocoo()
nz_mask = A.data != 0
return (A.row[nz_mask], A.col[nz_mask])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment