请问你能给出具体的修改后的代码吗
时间: 2024-02-28 15:55:19 浏览: 110
Android Studio使用Kotlin时,修改代码后运行不生效的解决方法
当然可以,以下是修改后的代码:
```
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# 读取数据
df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx")
# 构建边列表
edges = []
for i in range(len(df)):
edge = {
"id": df.loc[i, "边的编号"],
"tail": df.loc[i, "边的尾节点"],
"head": df.loc[i, "边的头节点"],
"length": df.loc[i, "长度"],
"capacity": df.loc[i, "容量"]
}
edges.append(edge)
# 绘制网络图
plt.figure(figsize=(15,15))
G = nx.DiGraph()
for edge in edges:
G.add_edge(edge["tail"], edge["head"], weight=edge["length"])
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.5)
plt.show()
# 计算最短路径和经过的边
all_pairs = nx.all_pairs_dijkstra_path(G)
rows = []
for start_node, paths in all_pairs:
for end_node, path in paths.items():
path_edges = [edges[G[path[i]][path[i+1]]['id']-1]['id'] for i in range(len(path)-1)]
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': len(path)-1, '经过的边': ','.join(path_edges)})
# 写入 excel 表格
df_result = pd.DataFrame(rows)
df_result.to_excel('all_pairs.xlsx', index=False)
```
这段代码中,我们使用 `nx.all_pairs_dijkstra_path` 方法计算所有顶点对之间的最短路径,并遍历每个路径,获取它经过的所有边的编号,并将它们用逗号分隔成一个字符串,最后将它们作为一列写入 excel 表格。
阅读全文