簡體   English   中英

Networkx 忽略最短路徑中具有特定屬性值的節點

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM