[SciPy-dev] Dense to sparse operator

Robert Cimrman cimrman3 at ntc.zcu.cz
Mon Feb 13 04:36:00 CST 2006


Nils Wagner wrote:
> Nils Wagner wrote:
> 
>>Hi all,
>>
>>How can I "transform" a dense matrix into a sparse matrix in scipy ?
>>
>>Nils
>>
>>
>>_______________________________________________
>>Scipy-dev mailing list
>>Scipy-dev at scipy.net
>>http://www.scipy.net/mailman/listinfo/scipy-dev
>> 
>>
>>>>A
> 
> array([[ 2. , -0.9,  0. ,  0. ],
>        [-1.1,  2. , -0.9,  0. ],
>        [ 0. , -1.1,  2. , -0.9],
>        [ 0. ,  0. , -1.1,  2. ]])
> 
>>>>Asp=csc_matrix(A)
>>>>Asp
> 
> <4x4 sparse matrix of type '<type 'float64scalar'>'
>         with 10 stored elements (space for 10)
>         in Compressed Sparse Column format>
> 
>>>>print Asp
> 
>   (0, 0)        2.0
>   (1, 0)        -1.1
>   (0, 1)        -0.9
>   (1, 1)        2.0
>   (2, 1)        -1.1
>   (1, 2)        -0.9
>   (2, 2)        2.0
>   (3, 2)        -1.1
>   (2, 3)        -0.9
>   (3, 3)        2.0
> 
>>>>A.csc_matrix()
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'numpy.ndarray' object has no attribute 'csc_matrix'
> 
> The opposite way round works fine
> 
> 
>>>>Asp.todense()
> 
> array([[ 2. , -0.9,  0. ,  0. ],
>        [-1.1,  2. , -0.9,  0. ],
>        [ 0. , -1.1,  2. , -0.9],
>        [ 0. ,  0. , -1.1,  2. ]])
> 
> Nils

Hi Nils,
the problem here is, that the dense matrices (or numpy arrays) are not 
on the same level as the sparse matrix module - the sparse matrix module 
knows about and uses the numpy arrays, while the numpy arrays are not 
aware of the sparse matrix module.

That is why you can do
sparseA.todense()
and you cannot do
denseA.tosparse() or something similar (but it would be nice :-))
- use instead the form
sparseA = csc_matrix( densaA ), or any other sparse matrix construcotr, 
just like you did.

r.




More information about the Scipy-dev mailing list