1 回答

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
添加回答
舉報