这段代码报错: KeyError: 'id'
时间: 2023-12-11 14:05:47 浏览: 177
抱歉,这是我的疏忽。在 `G.add_edge` 函数中需要添加 `id` 属性,但是不是所有边都有 `id` 属性,所以有些边没有 `id` 属性,导致 `KeyError`。为了解决这个问题,需要在添加边时先判断该边是否有 `id` 属性,如果有就添加,没有就不添加。修改后的代码如下:
```
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 = {
"tail": df.loc[i, "边的尾节点"],
"head": df.loc[i, "边的头节点"],
"length": df.loc[i, "长度"],
"capacity": df.loc[i, "容量"]
}
if "边的编号" in df.columns:
edge["id"] = df.loc[i, "边的编号"]
edges.append(edge)
plt.figure(figsize=(15,15))
G = nx.DiGraph()
for edge in edges:
if "id" in edge:
G.add_edge(edge["tail"], edge["head"], weight=edge["length"], id=edge["id"])
else:
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)
plt.show()
all_pairs = dict(nx.all_pairs_dijkstra_path_length(G))
rows = []
for start_node, dist_dict in all_pairs.items():
for end_node, dist in dist_dict.items():
path_edges = []
if start_node != end_node:
path = nx.shortest_path(G, start_node, end_node)
for i in range(len(path)-1):
tail = path[i]
head = path[i+1]
if "id" in G[tail][head]:
path_edges.append(G[tail][head]['id'])
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': dist, '经过边的编号': path_edges})
df_result = pd.DataFrame(rows)
df_result.to_excel('all_pairs.xlsx', index=False)
```
这样修改后,就可以在添加边时判断边是否有 `id` 属性,从而避免 `KeyError` 异常了。
阅读全文