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) #nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.3) 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(): rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': dist}) df_result = pd.DataFrame(rows) df_result.to_excel('all_pairs.xlsx', index=False)请问在写入excel的时候,能否把经过的边的编号一起写入呢?麻烦给下修改后的代码,谢谢你!
时间: 2024-02-17 07:05:23 浏览: 61
可以在遍历最短路径的时候记录下经过的边的编号,然后将其存储到结果表格中。以下是修改后的代码:
```
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)
#plt.draw()
plt.show()
all_pairs = dict(nx.all_pairs_dijkstra_path(G))
rows = []
for start_node, paths in all_pairs.items():
for end_node, path in paths.items():
path_edges = []
for i in range(len(path)-1):
edge_id = G[path[i]][path[i+1]]['id']
path_edges.append(edge_id)
row = {
'起始节点': start_node,
'终止节点': end_node,
'最短路径长度': nx.dijkstra_path_length(G, start_node, end_node),
'经过的边编号': path_edges
}
rows.append(row)
df_result = pd.DataFrame(rows)
df_result.to_excel('all_pairs.xlsx', index=False)
```
修改后的代码中,我们在遍历最短路径时,记录下了经过的边的编号,并将其存储到结果表格的“经过的边编号”一列中。
阅读全文