【问题标题】:Networkx: Calculating and storing shortest paths on a graph to a Pandas Data frameNetworkx:计算图表上的最短路径并将其存储到 Pandas 数据框
【发布时间】:2018-11-25 19:09:46
【问题描述】:

我有一个熊猫数据框,如下所示。该框架中还有更多与任务无关的列。 id 列显示句子ID,而e1e2 列包含句子的实体(=words)及其在r 列中的关系

id     e1        e2          r
10     a-5       b-17        A 
10     b-17      a-5         N
17     c-1       a-23        N
17     a-23      c-1         N
17     d-30      g-2         N
17     g-20      d-30        B

我还为每个句子创建了一个图表。该图是从看起来有点像这样的边列表创建的

[('wordB-5', 'wordA-1'), ('wordC-8', 'wordA-1'), ...]

所有这些边都在一个列表(列表)中。该列表中的每个元素都包含每个句子的所有边。意思是list[0]有句子0的边缘等等。

现在我想执行如下操作:

graph = nx.Graph(graph_edges[i])
shortest_path = nx.shortest_path(graph, source="e1", 
target="e2")
result_length = len(shortest_path)
result_path = shortest_path

对于数据框中的每一行,我想计算最短路径(从e1 中的实体到e2 中的实体,并将所有结果保存在 DataFrame 的新列中,但我不知道该怎么做。

我尝试使用诸如此类的结构

e1 = DF["e1"].tolist()
e2 = DF["e2"].tolist()
for id in Df["sentenceID"]:
    graph = nx.Graph(graph_edges[id])
    shortest_path = nx.shortest_path(graph,source=e1, target=e2)
result_length = len(shortest_path)
result_path = shortest_path

要创建数据,但它说目标不在图表中。

new df=

id     e1        e2          r     length     path
10     a-5       b-17        A       4         ..
10     b-17      a-5         N       4         ..
17     c-1       a-23        N       3         ..
17     a-23      c-1         N       3         ..
17     d-30      g-2         N       7         ..
17     g-20      d-30        B       7         ..

【问题讨论】:

    标签: python list pandas networkx


    【解决方案1】:

    这里有一种方法来做你想做的事,分三个不同的步骤,以便更容易遵循。

    • 第 1 步:从边列表构建 networkx 图形对象。
    • 第 2 步:创建一个包含 2 列的数据框(对于此 DF 中的每一行,我们希望从 e1 列到 e2 中的实体的最短距离和路径)
    • 第 3 步:逐行计算 DF,计算最短路径和长度。将它们作为新列存储在 DF 中。

    第 1 步:构建图并逐一添加边

    import pandas as pd
    import networkx as nx
    import matplotlib.pyplot as plt
    
    elist = [[('a-5', 'b-17'), ('b-17', 'c-1')], #sentence 1
             [('c-1', 'a-23'), ('a-23', 'c-1')], #sentence 2
             [('b-17', 'g-2'), ('g-20', 'c-1')]] #sentence 3
    
    graph = nx.Graph()
    
    for sentence_edges in elist:
        for fromnode, tonode in sentence_edges:
            graph.add_edge(fromnode, tonode)
    
    nx.draw(graph, with_labels=True, node_color='lightblue')
    

    第 2 步:创建所需距离的数据框

    #Create a data frame to store distances from the element in column e1 to e2
    DF = pd.DataFrame({"e1":['c-1', 'a-23', 'c-1', 'g-2'],
                 "e2":['b-17', 'a-5', 'g-20', 'g-20']})
    DF
    

    第三步:计算最短路径和长度,并存入数据框

    这是最后一步。计算最短路径并存储它们。

    pathlist, len_list = [], [] #placeholders
    
    for row in DF.itertuples():
        so, tar = row[1], row[2]
        path = nx.shortest_path(graph, source=so, target=tar)
        length=nx.shortest_path_length(graph,source=so, target=tar)
        pathlist.append(path)
        len_list.append(length)
    
    #Add these lists as new columns in the DF
    DF['length'] = len_list
    DF['path'] = pathlist
    

    这会产生所需的结果数据框:

    希望对你有所帮助。

    【讨论】:

      【解决方案2】:

      对于任何对解决方案感兴趣的人(感谢Ram Narasimhan):

       pathlist, len_list = [], []
       so, tar = DF["e1"].tolist(), DF["e2"].tolist()
       id = DF["id"].tolist()
      
       for _,s,t in zip(id, so, tar):
           graph = nx.Graph(graph_edges[_]) #Constructing each Graph
           try:
               path = nx.shortest_path(graph, source=s, target=t)
               length = nx.shortest_path_length(graph,source=s, target=t)
               pathlist.append(path)
               len_list.append(length)
           except nx.NetworkXNoPath:
               path = "No Path"
               length = "No Pathlength"
               pathlist.append(path)
               len_list.append(length)
      
       #Add these lists as new columns in the DF
       DF['length'] = len_list
       DF['path'] = pathlist
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        • 1970-01-01
        • 2013-03-30
        相关资源
        最近更新 更多