Skip to content

Instantly share code, notes, and snippets.

@oyamad
Last active November 8, 2019 11:31
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 oyamad/a87e4a2ab31b5ebc7c32 to your computer and use it in GitHub Desktop.
Save oyamad/a87e4a2ab31b5ebc7c32 to your computer and use it in GitHub Desktop.
Get indices of nonzero entries of a csr_matrix
import scipy.sparse
def csr_matrix_indices(S):
"""
Return a list of the indices of nonzero entries of a csr_matrix S
"""
major_dim, minor_dim = S.shape
minor_indices = S.indices
major_indices = np.empty(len(minor_indices), dtype=S.indices.dtype)
scipy.sparse._sparsetools.expandptr(major_dim, S.indptr, major_indices)
return zip(major_indices, minor_indices)
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
def csr_matrix_indices_gen(S):
"""
Generate the indices of nonzero entries of a csr_matrix S
"""
major_dim, minor_dim = S.shape
minor_indices = S.indices
for i in range(major_dim):
for j in range(S.indptr[i], S.indptr[i+1]):
major_index, minor_index = i, minor_indices[j]
yield major_index, minor_index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment