The following trick works for any operation that maps zero to zero and only for these operations, since it applies only to nonzero elements. Ie, it will work for sin and sqrt , but not for cos .
Let X be some CSR matrix ...
>>> from scipy.sparse import csr_matrix >>> X = csr_matrix(np.arange(10).reshape(2, 5), dtype=np.float) >>> XA array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.]])
Values โโof nonzero X.data elements:
>>> X.data array([ 1., 2., 3., 4., 5., 6., 7., 8., 9.])
which you can update on the spot:
>>> X.data[:] = np.sqrt(X.data) >>> XA array([[ 0. , 1. , 1.41421356, 1.73205081, 2. ], [ 2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ]])
Update . In recent versions of SciPy, you can do things like X.sqrt() , where X is the sparse matrix to get a new copy with the square roots of the elements in X