python networkx进行最短路径分析_python-Networkx:计算并存储图中到熊猫数据框的最短路径...

我有一个熊猫数据框,如下所示.该框架中还有许多与任务无关紧要的列. ID列显示句子ID,而e1和e2列包含句子的实体(=单词)及其在r列中的关系

id e1 e2 r

10 a-5 b-17 A

10 b-17 a-5 N

17 c-1 a-23 N

17 a-23 c-1 N

17 d-30 g-2 N

17 g-20 d-30 B

我还为每个句子创建了一个图表.该图是从看起来像这样的边列表中创建的

[(‘wordB-5′,’wordA-1’),(‘wordC-8′,’wordA-1’),…]

所有这些边都在一个列表中.该列表中的每个元素都包含每个句子的所有边.含义list [0]具有句子0的边缘,依此类推.

现在,我要执行以下操作:

graph = nx.Graph(graph_edges[i])

shortest_path = nx.shortest_path(graph, source="e1",

target="e2")

result_length = len(shortest_path)

result_path = shortest_path

对于数据框中的每一行,我想计算最短的路径(从e1中的实体到e2中的实体,并将所有结果保存在DataFrame中的新列中,但是我不知道该怎么做.

我尝试使用这些构造

e1 = DF["e1"].tolist()

e2 = DF["e2"].tolist()

for id in Df["sentenceID"]:

graph = nx.Graph(graph_edges[id])

shortest_path = nx.shortest_path(graph,source=e1, target=e2)

result_length = len(shortest_path)

result_path = shortest_path

创建数据,但表示目标不在图中.

new df=

id e1 e2 r length path

10 a-5 b-17 A 4 ..

10 b-17 a-5 N 4 ..

17 c-1 a-23 N 3 ..

17 a-23 c-1 N 3 ..

17 d-30 g-2 N 7 ..

17 g-20 d-30 B 7 ..

解决方法:

这是通过三种不同的步骤来做您想做的事情的一种方法,因此很容易遵循.

>步骤1:从边缘列表中构建networkx图形对象.

>步骤2:创建一个包含2列的数据框(对于该DF中的每一行,我们希望从e1列到e2中的实体的最短距离和路径)

>步骤3:逐行查找DF,计算最短路径和长度.将它们作为新列存储在DF中.

步骤1:建立图形并逐一添加边线

import pandas as pd

import networkx as nx

import matplotlib.pyplot as plt

elist = [[('a-5', 'b-17'), ('b-17', 'c-1')], #sentence 1

[('c-1', 'a-23'), ('a-23', 'c-1')], #sentence 2

[('b-17', 'g-2'), ('g-20', 'c-1')]] #sentence 3

graph = nx.Graph()

for sentence_edges in elist:

for fromnode, tonode in sentence_edges:

graph.add_edge(fromnode, tonode)

nx.draw(graph, with_labels=True, node_color='lightblue')

步骤2:建立所需距离的资料框

#Create a data frame to store distances from the element in column e1 to e2

DF = pd.DataFrame({"e1":['c-1', 'a-23', 'c-1', 'g-2'],

"e2":['b-17', 'a-5', 'g-20', 'g-20']})

DF

步骤3:计算最短路径和长度,并存储在数据框中

这是最后一步.计算最短路径并存储它们.

pathlist, len_list = [], [] #placeholders

for row in DF.itertuples():

so, tar = row[1], row[2]

path = nx.shortest_path(graph, source=so, target=tar)

length=nx.shortest_path_length(graph,source=so, target=tar)

pathlist.append(path)

len_list.append(length)

#Add these lists as new columns in the DF

DF['length'] = len_list

DF['path'] = pathlist

产生所需的结果数据帧:

希望这对您有所帮助.

标签:pandas,list,networkx,python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值