Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine matrix and sparse matrix

How can you add a 1-column matrix to a sparse matrix, or add a sparse matix to a column matrix (either way)? It shouldn't replace the data, just join it into one data type.

The sparse matrix:

>>print type(X)
>>print X.shape
<class 'scipy.sparse.csr.csr_matrix'>
(53, 6596)

The column to add:

>>print type(Y)
>>print Y.shape
<class 'numpy.matrixlib.defmatrix.matrix'>
(53, 1)

How can you do this?

like image 713
Zach Avatar asked Feb 20 '23 07:02

Zach


1 Answers

from the docs, it seems to me that you're looking for hstack / vstack from the scipy.sparse module:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy.sparse as ssp
>>> print ssp.hstack.__doc__

    Stack sparse matrices horizontally (column wise)

    Parameters
    ----------
    blocks
        sequence of sparse matrices with compatible shapes
    format : string
        sparse format of the result (e.g. "csr")
        by default an appropriate sparse matrix format is returned.
        This choice is subject to change.

    See Also
    --------
    vstack : stack sparse matrices vertically (row wise)

    Examples
    --------
    >>> from scipy.sparse import coo_matrix, vstack
    >>> A = coo_matrix([[1,2],[3,4]])
    >>> B = coo_matrix([[5],[6]])
    >>> hstack( [A,B] ).todense()
    matrix([[1, 2, 5],
            [3, 4, 6]])


>>>
like image 92
ev-br Avatar answered Feb 22 '23 05:02

ev-br