【问题标题】:Shortest path from A to B in a weighted and directed 2D pandas csv graph加权和有向 2D pandas csv 图中从 A 到 B 的最短路径
【发布时间】:2021-09-30 19:34:58
【问题描述】:

我有一个用 pandas 创建并保存为 csv 文件的 2D n x n 矩阵表示的加权图

索引和列标题是代表节点的数字。边是连接两个节点的权重

例如:{1232: {1232: inf, 2342: 12, 45654: inf, 45678: 21}} 等等

我想实现 shortestRoute 算法,它将返回从节点 a 到 b 的最短(最小总权重)路径的节点。

所以它会返回 1232 -> 2345 -> 45678

我知道我可以实现 Dijkstra 以获得最小的权重,但不知道如何获得路径

inf 指的是没有边连接的两个节点

【问题讨论】:

  • Dijkstra 的算法也能帮你找到路径
  • 有没有 Dijkstra 的 python 库

标签: python pandas graph dijkstra


【解决方案1】:

用你的数据+一个额外的优势做一个小例子。

import pandas as pd
import networkx as nx

so = pd.DataFrame({
    "source": [1232, 1232 , 1232, 2345 ],
    "target": [2342, 45678, 2345, 45678],
    "weight": [12  , 21   ,    1,      1]
})

G = nx.from_pandas_edgelist(so, source="source", target="target", edge_attr="weight")

# added since `nx.draw_networkx_edge_labels` requires `pos`
pos = nx.spring_layout(G)

nx.draw(G, pos=pos, with_labels=True, node_size=500)

# taken from https://stackoverflow.com/a/67145811/6509519
nx.draw_networkx_edge_labels(G, pos=pos);

nx.shortest_path(G, source=1232, target=45678, weight="weight", method="dijkstra")
# >>> [1232, 2345, 45678]

【讨论】:

  • 有没有办法绘制图形以使其同时显示边的权重?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
相关资源
最近更新 更多