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) plt.figure(figsize=(10,8)) 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)) 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, label_pos=0.3) plt.show()修改代码将所有顶点对间最短路长度写入一个新的excel
时间: 2023-10-30 15:04:44 浏览: 83
好的,您可以使用`pandas`库将结果写入Excel文件中。下面是具体的代码实现:
```python
import pandas as pd
import networkx as nx
# 从Excel中读入边列表
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["tail"], edge["head"], weight=edge["length"])
# 使用Floyd算法求解所有顶点对之间的最短路长度
dist = nx.floyd_warshall(G)
# 将结果写入Excel文件中
rows = []
for i, row in enumerate(dist):
for j, value in enumerate(row):
rows.append({"起始节点": i, "终止节点": j, "最短路长度": value})
df_result = pd.DataFrame(rows)
df_result.to_excel(r"C:\Users\li'yi'jie\Desktop\最短路径结果.xlsx", index=False)
```
其中,我们使用`pandas`库的`DataFrame`类来创建一个数据框,然后将每个顶点对之间的最短路长度作为一行数据添加到数据框中。最后,使用`to_excel`方法将数据框写入Excel文件中。
需要注意的是,在使用`to_excel`方法时,我们需要将`index`设置为`False`,否则会将每行数据的索引作为Excel文件中的一列数据写入。
阅读全文