Skip to content

Instantly share code, notes, and snippets.

@harryscholes
Created June 2, 2017 11:13
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 harryscholes/6a6d2199dd85b4f3286012324e1247e3 to your computer and use it in GitHub Desktop.
Save harryscholes/6a6d2199dd85b4f3286012324e1247e3 to your computer and use it in GitHub Desktop.
Efficient boolean indexing of SciPy spare matrices
from scipy import sparse
# generate a random sparse matrix
M = sparse.random(100,100)
M
# <100x100 sparse matrix of type '<class 'numpy.float64'>'
# with 100 stored elements in COOrdinate format>
# create boolean array of the data stord in the sparse matrix
mask = M.data < 0.7
# manipulate the values in the matrix that meet the condition
M.data[mask] = 0
# remove the newly assigned zero values to sparsify the matrix
M.eliminate_zeros()
M
# <100x100 sparse matrix of type '<class 'numpy.float64'>'
# with 31 stored elements in COOrdinate format>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment