[英]Networkx ignore nodes with certain values for attributes in shortest path
我想从 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
节点,情况就不会如此。 我看不到如何修改它,有没有一种规范的方式而不是编码我自己的最短路径?
谢谢!
我不知道开箱即用的解决方案,但您可以从具有所需属性的所有节点创建子图(快速和肮脏的实现):
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')
编辑: @Joel 正确指出,这个答案可能会给出错误的结果。 为了避免这些,您可以查询只有具有正确属性的边的图的副本:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.