为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英4014372 2024-01-16 15:07:49
我正在尝试使用 networkx 来确定源节点和目标节点之间的最短加权路径。为此,我正在使用nx.shortest_path. 但是,我无法让它正常运行。以下类似于我的设置:import pandas as pdimport networkx as nxdf = 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 gg = 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']")任何帮助将不胜感激!
查看完整描述

1 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

您使图表的创建过于复杂。您可以使用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


查看完整回答
反对 回复 2024-01-16
  • 1 回答
  • 0 关注
  • 32 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信