【发布时间】:2018-11-25 19:09:46
【问题描述】:
我有一个熊猫数据框,如下所示。该框架中还有更多与任务无关的列。 id 列显示句子ID,而e1 和e2 列包含句子的实体(=words)及其在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 ..
【问题讨论】:
标签: python list pandas networkx