求 NetworkX 中加权图的最短路径长度

我正在尝试使用 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(加权距离)。我怀疑这是因为我错误地引用了权重属性。但是,我不确定我应该怎么做。


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


任何帮助将不胜感激!


慕桂英4014372
浏览 39回答 1
1回答

Qyouu

您使图表的创建过于复杂。您可以使用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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python