import pandas as pd 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) G = nx.DiGraph() for edge in edges: G.add_edge(edge['边的尾节点'], edge['边的头节点'], weight=edge['长度']) all_pairs = dict(nx.all_pairs_dijkstra_path_length(G)) pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True) labels = nx.get_edge_attributes(G, '长度') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels) plt.show(),报错:KeyError: '边的尾节点',请问如何解决
时间: 2023-08-09 10:12:21 浏览: 401
根据你提供的代码和报错信息,问题出在以下代码段:
```
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)
```
报错提示是`KeyError: '边的尾节点'`,说明在df中不存在名为'边的尾节点'的列。进一步分析,可能是由于列名中的单引号和双引号混用导致的。你可以将代码中的单引号替换成双引号,或者直接去掉单引号,例如:
```
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)
```
或者:
```
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)
```
修改后再运行代码看看是否解决了问题。
阅读全文