【问题标题】:Creating a sparse matrix from a dataframe with edges从具有边的数据帧创建稀疏矩阵
【发布时间】:2018-05-06 07:50:55
【问题描述】:

假设我有一个 csv 文件,其中包含以下格式的数据:

甲乙

C D

A C

D F

GH

K 米

MA

其中每一行给出节点1和节点2之间的无向边。我目前正在将其作为数据框读取,但想将其转换为稀疏矩阵。有没有一种快速简便的方法来做到这一点而无需循环?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    要直接构造一个 scipy 稀疏矩阵,您必须将字母映射到唯一索引上,例如A == 1B == 2

    In [202]: txt='''A B
         ...: 
         ...: C D
         ...: 
         ...: A C
         ...: 
         ...: D F
         ...: 
         ...: G H
         ...: 
         ...: K M
         ...: 
         ...: M A'''.splitlines()
    In [203]: values = 'ABCDEFGHIJKLM'
    In [204]: data = [x.split() for x in txt if x]
    In [205]: data = [[values.index(x) for x in row] for row in data]
    In [206]: data
    Out[206]: [[0, 1], [2, 3], [0, 2], [3, 5], [6, 7], [10, 12], [12, 0]]
    

    所以现在我们有了坐标对。有多种方法可以从这些构造稀疏矩阵。从概念上讲,也许最简单的方法是使用lil 格式矩阵(迭代构造的最佳格式)进行迭代:

    In [207]: from scipy import sparse
    In [208]: M = sparse.lil_matrix((len(values),len(values)),dtype=int)
    In [209]: for row in data:
         ...:     M[tuple(row)] = 1
         ...:     
    In [210]: M
    Out[210]: 
    <13x13 sparse matrix of type '<class 'numpy.int64'>'
        with 7 stored elements in LInked List format>
    In [211]: M.A
    Out[211]: 
    array([[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-10
      • 2014-11-30
      • 2017-03-31
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多