【问题标题】:extra column and row while converting to lil matrix转换为 lil 矩阵时额外的列和行
【发布时间】:2020-04-26 14:34:00
【问题描述】:

这是参考问题的第二部分:pandas dataframe to coo matrix and to lil matix

import scipy.sparse as sps
print(len(networks[0]), len(networks[1]), networks[0].nunique(), networks[1].nunique())
667966 667966 10312 10312
networks[:5]



     0   1
0   176 1
1   233 1
2   283 1
3   371 1
4   394 1

制作行和列标签

rows = networks[0]
cols = networks[1]



matrix = sps.coo_matrix((networks[2], (rows, cols)))
d=matrix.tolil()
d

生成

<10313x10313 sparse matrix of type '<class 'numpy.uint32'>'
    with 667966 stored elements in LInked List format>

我的问题是为什么形状 10313x10313 而不是 10312x10312 因为有 10312 独特的元素?

请注意networks[[0, 1]] 是边。

【问题讨论】:

    标签: pandas scipy networkx sparse-matrix


    【解决方案1】:

    看一个小例子:

    In [458]: rows=np.arange(5); cols=rows; data = np.ones(len(rows), int)          
    In [459]: M = sparse.coo_matrix((data, (rows, cols)))                           
    In [460]: M                                                                     
    Out[460]: 
    <5x5 sparse matrix of type '<class 'numpy.int64'>'
        with 5 stored elements in COOrdinate format>
    In [461]: max(rows)                                                             
    Out[461]: 4
    
    In [463]: M.row                                                                 
    Out[463]: array([0, 1, 2, 3, 4], dtype=int32)
    In [464]: print(M)                                                              
      (0, 0)    1
      (1, 1)    1
      (2, 2)    1
      (3, 3)    1
      (4, 4)    1
    
    In [465]: M.A                                                                   
    Out[465]: 
    array([[1, 0, 0, 0, 0],
           [0, 1, 0, 0, 0],
           [0, 0, 1, 0, 0],
           [0, 0, 0, 1, 0],
           [0, 0, 0, 0, 1]])
    

    【讨论】:

    • 是的,我理解这个例子。我不明白的是那个额外的维度是从哪里来的?
    • 是的,由于某种原因,这搞砸了,在创建 coo 矩阵时添加了一个空列表。不知道怎么可能
    【解决方案2】:

    要求所有的都有一个索引:

    networks.set_index([0, 1], inplace=True)
    Ntw= sps.coo_matrix((networks[2], (networks.index.labels[0], networks.index.labels[1])))
    d=Ntw.tolil()
    Ntw.shape
    

    生成:

    <10312x10312 sparse matrix of type '<class 'numpy.int64'>'
        with 667966 stored elements in LInked List format>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2017-02-21
      • 2010-12-03
      • 1970-01-01
      • 2018-03-01
      相关资源
      最近更新 更多