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-18 09:58:53 浏览: 90
初始化信息-详解pandas库pd.read_excel操作读取excel文件参数整理与实例
可以的,修改代码如下:
```
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"], id=edge["id"]) # 在这里添加边的编号
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]
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)
```
这样修改后,在生成的 Excel 文件中,会有一列名为“经过边的编号”的列,其中每个单元格中存储着对应路径上的边的编号。
阅读全文