上述代码报错:KeyError: 'id'
时间: 2023-12-21 10:03:42 浏览: 126
非常抱歉,我的代码有误。在获取边的编号时,应该使用 `G[path[i]][path[i+1]]['id']`,而不是 `G[path[i]][path[i+1]]['id']-1`。因为 `G[path[i]][path[i+1]]['id']` 已经是边的编号了,不需要再减 1。
以下是修改后的代码:
```
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']]['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)
```
这段代码中,我们使用 `G[path[i]][path[i+1]]['id']` 获取经过的每条边的编号,并将它们存储在一个列表中,最后将它们用逗号分隔成一个字符串,作为一列写入 excel 表格。
阅读全文