【问题标题】:Find the shortest path length of a weighted graph in NetworkX在 NetworkX 中找到加权图的最短路径长度
【发布时间】:2020-10-27 13:59:15
【问题描述】:

我正在尝试使用 networkx 来确定源节点和目标节点之间的最短加权路径。为此,我使用nx.shortest_path。但是,我无法让它正常工作。

以下类似于我的设置:

import pandas as pd
import networkx as nx

df = pd.DataFrame({'F': ['a','b','c','d','d','e'], # f node identifier
                   'T': ['b','c','d','e','f','f'], # t node identifier
                   'weight': [1.2,5.2,2.7,2.8,1.3,7.4], # weight for shortest path algorithm
                   'dummy': ['q','w','e','r','t','y']}) # dummy variable

网络构建发生在一个函数中,因为如果我让它工作,它将应用于几个不同的数据集!这也是为什么属性作为字典而不是单独添加的原因。

def build_network(df=None, column_names=None):
    g = nx.DiGraph()
    
    for i,row in df.iterrows():
          g.add_edge(row[column_names['F']],row[column_names['T']],attributes=row[column_names['attributes']].to_dict())
           
    return g

g = build_network(df, column_names={'F':'F',
                                    'T':'T',
                                    'attributes':['weight','dummy']})

最后应用shortest_path_length算法,表示长度为2(边数),而不是4.0(加权距离)。我怀疑这是因为我错误地引用了 weight 属性。但是,我不确定我应该怎么做。

nx.shortest_path_length(G=g, source='c', target='f', weight="['attributes']['weight']")

任何帮助将不胜感激!

【问题讨论】:

    标签: python dictionary network-programming networkx


    【解决方案1】:

    您使图表的创建过于复杂。您可以使用nx.from_pandas_edgelist 以更简单的方式从数据框创建图形(包括边缘属性)并找到最短路径长度:

    G = nx.from_pandas_edgelist(df, source='F', target='T', edge_attr=['weight','dummy'], 
                                create_using=nx.DiGraph)
    
    G.edges(data=True)
    # EdgeDataView([('a', 'b', {'weight': 1.2, 'dummy': 'q'}), 
    #               ('b', 'c', {'weight': 5.2, 'dummy': 'w'})...
    
    nx.shortest_path_length(G, source='c', target='f', weight='weight')
    # 4.0
    

    仔细研究您的方法,问题在于您如何在nx.shortest_path_length 中指定权重。您正在使用"['attributes']['weight']",此时weight 参数应设置为指定权重属性名称的字符串。所以在你的情况下,"weight"

    因此您得到的结果与以下相同:

    nx.shortest_path_length(G=g, source='c', target='f', weight=None)
    # 2
    

    而你应该像上面那样做:

    nx.shortest_path_length(G, source='c', target='f', weight='weight')
    # 4.0
    

    【讨论】:

    • 感谢 yatu,nx.from_pandas_edgelist 这很好用,应该很容易与其余代码合并!
    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2020-04-08
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多