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"]) 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时,将其经过的边的编号一起写入excel?
时间: 2024-01-02 12:03:49 浏览: 502
解决Python pandas df 写入excel 出现的问题
可以在遍历所有起点和终点对的最短路径时,记录下路径上经过的边的编号,然后将其一起写入Excel。可以将以下代码添加到原有代码中:
```
for start_node, path_dict in nx.all_pairs_dijkstra_path(G):
for end_node, path in path_dict.items():
path_edges = []
for i in range(len(path)-1):
tail = path[i]
head = path[i+1]
edge_id = G[tail][head]['id']
path_edges.append(edge_id)
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': nx.dijkstra_path_length(G, start_node, end_node), '经过的边的编号': path_edges})
```
这段代码将路径上经过的边的编号存储在一个列表中,然后将其作为一个新的列添加到Excel表格中。需要在创建DataFrame对象时将列名加入到rows中:
```
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': nx.dijkstra_path_length(G, start_node, end_node), '经过的边的编号': path_edges})
```
最后将DataFrame对象写入Excel文件中时,也要将这个新的列加入到Excel表格中:
```
df_result = pd.DataFrame(rows, columns=['起始节点', '终止节点', '最短路径长度', '经过的边的编号'])
df_result.to_excel('all_pairs.xlsx', index=False)
```
阅读全文