Element-wise power of scipy.sparse matrix Element-wise power of scipy.sparse matrix numpy numpy

Element-wise power of scipy.sparse matrix


I just ran into the same question and find that sparse matrix now supports element-wise power. For the case above, it should be:

 X.power(2)


This is a little low-level, but for element-wise operations you can work with the underlying data array directly:

>>> import scipy.sparse>>> X = scipy.sparse.rand(1000,1000, density=0.003)>>> X = scipy.sparse.csr_matrix(X)>>> Y = X.copy()>>> Y.data **= 3>>> >>> abs((X.toarray()**3-Y.toarray())).max()0.0