Search code examples
pythonnumpyscipysparse-matrix

How to do operations with two vectors of different format in python


One of my vector is in format scipy.sparse.csr.csr_matrix, the other is numpy.ndarray. I have an experimental code below:

import numpy as np
from scipy.sparse import csr_matrix

x = np.arange(5)+1
y = [1, 0, 0, 1, 2]
y = csr_matrix(y)
print type(x)
print type(y)

z = np.true_divide(y,x)
print z.shape

I get z.shape = (5L,) and don't know what it means. If I print z it tells me its a row vector with 3 elements in it. How can I print the numerical result, e.g. the 1*5 vector from z? I'm new to Python and these math packages, just want to learn something about the sparse matrix operations. My problem is how to do operations like this right and efficiently, since I guess there is a way without getting sparse representations back to dense every time.

Thanks!


Solution

  • You could do this:

    import numpy as np
    from scipy.sparse import csr_matrix
    
    x = np.arange(5)+1
    
    y = [1, 0, 0, 1, 2]
    y = csr_matrix(y)
    
    x2 = 1.0 / np.matrix(x)
    
    z = y.multiply(x2)
    

    Result:

    >>> z
    matrix([[ 1.  ,  0.  ,  0.  ,  0.25,  0.4 ]])