合并矩阵和稀疏矩阵

4
您如何将一个1列矩阵添加到一个稀疏矩阵中,或将一个稀疏矩阵添加到一个列矩阵中(无论哪种方式)?它不应该替换数据,只需要将其合并成一种数据类型。
稀疏矩阵:
>>print type(X)
>>print X.shape
<class 'scipy.sparse.csr.csr_matrix'>
(53, 6596)

要添加的列:
>>print type(Y)
>>print Y.shape
<class 'numpy.matrixlib.defmatrix.matrix'>
(53, 1)

你如何实现这个目标?

1个回答

8

从文档中看来,你好像正在寻找scipy.sparse模块中的hstack / vstack函数:

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]])


>>>

虽然这里的文档说block应该是“稀疏矩阵序列”,但似乎传入混合的numpy.arrayscipy.sparse也没问题。唯一的副作用是输出矩阵格式可能不是预期的类型,应该指定format来强制进行格式转换。 - zaxliu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接