Networkx忽略在最短路径中具有特定属性值的节点

2024-04-24 13:26:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从a和D计算图中的最短路径,但只考虑具有给定属性的节点。例如:

import pandas as pd
import networkx as nx

cols = ['node_a','node_b','travel_time','attribute']

data = [['A','B',3,'attribute1'],
        ['B','C',1,'attribute1'],
        [ 'C','D',7,'attribute1'],
         ['D','E',3,'attribute1'],
         ['E','F',2,'attribute1'],
         ['F','G',4,'attribute1'],
         ['A','L',4,'attribute2'],
         ['L','D',3,'attribute2']
         ]
edges = pd.DataFrame(data)
edges.columns = cols
G=nx.from_pandas_dataframe(edges,'node_a','node_b', ['travel_time','attribute'])

如果我想计算从A到D的最短路径,默认方法是

nx.shortest_path(G,'A','D',weight='travel_time')

这可以给我['A', 'L', 'D'],但如果我只想考虑带有attribute1的节点,就不会是这种情况。我不知道如何修改它,但有一个规范的方法,而不是编码我自己的最短路径?你知道吗

谢谢!你知道吗


Tags: import路径nodepandasdata节点timeas
1条回答
网友
1楼 · 发布于 2024-04-24 13:26:22

我不知道开箱即用的解决方案,但您可以从所有具有所需属性的节点创建一个子图(快速而肮脏的实现):

edges = [(a,b) for (a,b,e) in G.edges(data=True) if e['attribute']=='attribute1']
nodes = []
for a,b in edges:
    nodes += [a,b]

nx.shortest_path(G.subgraph(nodes),'A','D',weight='travel_time')

编辑:@乔尔正确地指出,这个答案可能会给出错误的结果。 要避免这些情况,可以查询仅具有具有正确属性的边的图的副本:

H = G.copy()
edges_to_remove = [e for e in H.edges(data=True) if not e['attribute']=='attribute1']
H.remove_edges_from(edges_to_remove)
nx.shortest_path(H,'A','D',weight='travel_time')

Edit2:根据这个想法,我认为可以通过从原始图形中删除并重新添加边来加快速度,而无需复制:

edges_to_remove = [e for e in G.edges(data=True) if not e['attribute']=='attribute1']
G.remove_edges_from(edges_to_remove)
nx.shortest_path(G,'A','D',weight='travel_time')
G.add_edges_from(edges_to_remove)

相关问题 更多 >