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 12:04:44 浏览: 38
好的,您可以使用`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文件中的一列数据写入。

相关推荐

import pandas as pd import numpy as np import networkx as nx import matplotlib.pyplot as plt # 读取Excel文件中的邻接矩阵 adjacency_matrix = pd.read_excel('output.xlsx', index_col=0) # 将邻接矩阵转换为numpy数组 adjacency_matrix = adjacency_matrix.to_numpy() # 创建有向图对象 G = nx.DiGraph(adjacency_matrix) def preprocess(G): p = 0 directedGraph = nx.DiGraph() for u in G.nodes(): for v in G.neighbors(u): if (v != u): propProb = G.number_of_edges(u, v) / G.degree(v) directedGraph.add_edge(u, v, pp=propProb) return directedGraph def simulate(G, seedNode, propProbability): newActive = True currentActiveNodes = seedNode.copy() newActiveNodes = set() activatedNodes = seedNode.copy() influenceSpread = len(seedNode) while newActive: for node in currentActiveNodes: for neighbor in G.neighbors(node): if neighbor not in activatedNodes: if G[node][neighbor]['pp'] > propProbability: newActiveNodes.add(neighbor) activatedNodes.append(neighbor) influenceSpread += len(newActiveNodes) if newActiveNodes: currentActiveNodes = list(newActiveNodes) newActiveNodes = set() else: newActive = False return influenceSpread def flipCoin(probability): return np.random.random() < probability # 可视化传播过程 def visualizePropagation(G, seedNode, propProbability): pos = nx.spring_layout(G) # 选择布局算法 labels = {node: node for node in G.nodes()} # 节点标签为节点名 colors = ['r' if node in seedNode else 'b' for node in G.nodes()] # 种子节点为红色,其他节点为蓝色 plt.figure(figsize=(10,6)) nx.draw_networkx_nodes(G, pos, node_color=colors) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos, labels) plt.title('Propagation Visualization') plt.show() # 示例用法 seedNode = [7,36,17] propProbability = 0.7 directedGraph = preprocess(G) influenceSpread = simulate(directedGraph, seedNode, propProbability) print("Influence Spread:", influenceSpread) visualizePropagation(directedGraph, seedNode, propProbability)修改这个代码使得输出图形节点之间间隔合理能够看清

import networkx as nx import numpy as np import pandas as pd import matplotlib.pyplot as plt import networkx as nx import random df=pd.read_csv("D:\级联失效\edges.csv") G=nx.from_pandas_edgelist(df,'from','to',create_using=nx.Graph()) nx.draw(G,node_size=300,with_labels=True) As=nx.adjacency_matrix(G) A=As.todense() def f(x): F=4*x*(1-x) return F n=len(A) r=2 ohxs=0.4 step=10 d=np.zeros([n,step]) for i in range(n): d[i,0]=np.sum(A[i]) x_intial=np.zeros([n,step]) for i in range(n): x_intial[i,0]=random.random() np.set_printoptions(precision=5) h_a=100 H=np.zeros([n,step]) D=np.zeros([n,step]) for i in range(n): Deg=0 for k in range(n): if k!=i: Deg=Deg+d[k,0] D[i,0]=Deg H[i,0]=d[i,0]/D[i,0]/h_a fail_scale=np.zeros(step) fail_scale[0]=1 node_rand_id=random.randint(0,n) r=2 x_intial[node_rand_id,0]=x_intial[node_rand_id,0]+r print(x_intial) fail_node=np.zeros(n) fail_node[node_rand_id]=1 print(fail_node) np.seterr(divide='ignore',invalid='ignore') for t in range(1,step): fail_node_id=[idx for (idx,val) in enumerate(fail_node) if val ==1] for i in range(n): sum=0 for j in range(n): sum = sum+A[i,j]*f(x_intial[j,t-1])/d[i] if i in fail_node_id: x_intial[i,t-1]=0 A[i,:]=0 A[:,i]=0 else: x_intial[i,t]=H[i,t-1]*abs((1-ohxs)*f(x_intial[i,t-1])+ohxs*sum) d[i,t]=np.sum(A[i]) Deg=0 for k in range(n): if k!=i: Deg=Deg+d[i,t] D[i,t]=Deg H[i,t]=d[i,t]/D[i,t]/h_a new_fail_id=[idx for (idx,val) in enumerate(x_intial[:,t]) if val>=1] fail_scale[t]=fail_scale[t-1]+len(new_fail_id) fail_node[new_fail_id]=1 x_intial[new_fail_id,t]=x_intial[new_fail_id,t]+r print(H[i,t]) print(fail_node) print(x_intial) plt.plot(fail_scale) plt.show()

最新推荐

recommend-type

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a
recommend-type

matlab建立计算力学课程的笔记和文件.zip

matlab建立计算力学课程的笔记和文件.zip
recommend-type

FT-Prog-v3.12.38.643-FTD USB 工作模式设定及eprom读写

FT_Prog_v3.12.38.643--FTD USB 工作模式设定及eprom读写
recommend-type

matlab基于RRT和人工势场法混合算法的路径规划.zip

matlab基于RRT和人工势场法混合算法的路径规划.zip
recommend-type

matlab基于matlab的两步定位软件定义接收机的开源GNSS直接位置估计插件模块.zip

matlab基于matlab的两步定位软件定义接收机的开源GNSS直接位置估计插件模块.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。