【问题标题】:combine matrix and sparse matrix组合矩阵和稀疏矩阵
【发布时间】:2012-09-02 19:46:22
【问题描述】:

如何将 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)

你怎么能做到这一点?

【问题讨论】:

    标签: python matrix numpy scipy sparse-matrix


    【解决方案1】:

    根据文档,在我看来,您正在寻找来自 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 强制格式转换。
    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多