[Numpy-discussion] How to apply Numpy ufunc to Scipy sparse matrices?

Pengkui Luo pengkui.luo at gmail.com
Sun Sep 11 04:03:26 EDT 2011

It seems that numpy universal functions only apply to ndarray (or dense
matrix). Is there a way to apply them to scipy sparse matrices also?

For example, suppose S is an large sparse matrix (lil_matrix format,
dtype=np.float). I want to get another sparse matrix B (of the same shape)
that represents the signs of corresponding entries of S.

I wrote down "B=np.sign(S)" first, but it did not give me the desired
output. I realized that np.sign() might not work for a sparse matrix, so I
have to convert S to a dense matrix, i.e.

B = np.sign( S.todense() )

However, converting a large sparse matrix to dense would easily eat up the
memory. Is there a way for np.sign (as well as other ufunc) to take a sparse
matrix as parameter, and return a sparse matrix?

(If I recall correctly, in Matlab all functions work on both dense matrices
and sparse matrices.)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20110911/4087a317/attachment.html>

More information about the NumPy-Discussion mailing list