【问题标题】:How to set items of a sparse matrix given the row and column indices?给定行和列索引,如何设置稀疏矩阵的项?
【发布时间】:2013-11-28 10:27:42
【问题描述】:

假设我有一个列表列表,其中每个子列表包括要设置为 1 的连续行的列索引。

indices = [[1,43,243],[2,34,276],...]

我的目的是设置符合给定索引的 scipy 稀疏矩阵的值。

例如:

对于第一行 1,43,243 列需要设置为 1 对于第二行 2,34,276 列需要设置为 1

如果这是一个愚蠢的问题,对不起。我只是一个从 Matlab 过渡到 scipy 的初学者。

【问题讨论】:

    标签: python numpy scipy sparse-matrix


    【解决方案1】:

    sparse 的几种矩阵类型都可以使用。来自sparse.csr_matrix 文档:http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

    >>> row = array([0,0,1,2,2,2])
    >>> col = array([0,2,2,0,1,2])
    >>> data = array([1,2,3,4,5,6])
    >>> csr_matrix( (data,(row,col)), shape=(3,3) ).todense()
    matrix([[1, 0, 2],
            [0, 0, 3],
            [4, 5, 6]])
    

    coo_matrix 也接受这个(data,(row,col)) 输入

    Matlab 提供了一种创建稀疏矩阵的类似方法,包括添加重复条目的业务(请参阅coo_matrix 文档底部的注释)。

    我想你想构建

    row = array([0,0,0, 1,1,1,2,2,2,....])
    col = array([1,43,243, 2,34,276,,...])  
    # col = col-1 # to change to 0 based indexing?
    data = array([1,1,1,...])
    

    例如:

    np.array(indices).ravel()
    # array([  1,  43, 243,   2,  34, 276])
    np.arange(2).repeat(3)
    # array([0, 0, 0, 1, 1, 1])
    np.ones(6)
    # array([ 1.,  1.,  1.,  1.,  1.,  1.])
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 2019-12-03
      • 2012-01-15
      • 2014-05-12
      • 2018-05-06
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多