Created
June 2, 2017 11:13
-
-
Save harryscholes/6a6d2199dd85b4f3286012324e1247e3 to your computer and use it in GitHub Desktop.
Efficient boolean indexing of SciPy spare matrices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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