代码之家  ›  专栏  ›  技术社区  ›  lpt

转换为lil矩阵时额外的列和行

  •  0
  • lpt  · 技术社区  · 5 年前

    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]] 是边缘。

    0 回复  |  直到 5 年前
        1
  •  0
  •   hpaulj    5 年前

    看一个小例子:

    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]])
    
        2
  •  0
  •   lpt    5 年前

    所有必需的都有一个索引:

    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>