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

Pengkui Luo pengkui.luo@gmail....
Sun Sep 11 14:27:54 CDT 2011

```On Sun, Sep 11, 2011 at 13:23, Pauli Virtanen <pav@iki.fi> wrote:

> Sun, 11 Sep 2011 03:03:26 -0500, Pengkui Luo wrote:
> [clip]
> > 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?
>
> For CSR, CSC, and DIA you can do
>
>        x.data = some_ufunc(x.data)
>
> to operate on the nonzero entries. If some_ufunc(0) == 0, that's all you
> need. Otherwise, the matrix becomes dense.
>
>        Pauli
>

Hi Pauli,

Thanks for your ".data" tip. It works!

def _test_ufunc():
import numpy as np
from scipy.sparse import csr_matrix
A = np.mat( '2 3 0 0; 0 0 0 6; 1 0 0 -7; 0 -2 -1 0' )
print 'A=\n', A
AS = csr_matrix(A)
AS.data = np.sign( AS.data )
print '\ntype(AS.data)=%s' % type( AS.data )
print '\nnp.sign(AS)=\n%s' % AS.todense()
print '\ntype(AS)=%s' % type(AS)

if __name__=="__main__":
_test_ufunc()

>>>

A=
[[ 2  3  0  0]
[ 0  0  0  6]
[ 1  0  0 -7]
[ 0 -2 -1  0]]

type(AS.data)=<type 'numpy.ndarray'>

np.sign(AS)=
[[ 1  1  0  0]
[ 0  0  0  1]
[ 1  0  0 -1]
[ 0 -1 -1  0]]

type(AS)=<class 'scipy.sparse.csr.csr_matrix'>

--Pengkui
-------------- next part --------------
An HTML attachment was scrubbed...