首页 > 解决方案 > 如何将一个图的边权重添加到 NetworkX 中不同图中的匹配边?

问题描述

我在networkx中有两个不同的图,一个图有边的总集合。另一个图是总边的子集。我将如何从边图的总集合中获取权重并将它们添加到新图中的匹配边?

#total edge collection
G.edges(data = True)

OutEdgeDataView([(1, 2, {'weight': 10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}), 
(2, 1, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0}), (3, 8, {'weight': 0}), (3, 2, {'weight': 0}), (4, 3, {'weight': 0}), (5, 2, {'weight': 0}), (6, 2, {'weight': 0}), 
(7, 3, {'weight': 0}), (8, 3, {'weight': 0})])
T = nx.Graph()
T.add_edges_from([(1, 2), (2, 3), (2, 5), (2, 6), (3, 8), (3, 4), (3, 7)])
T.edges(data = True)

EdgeDataView([(1, 2, {}), (2, 3, {}), (2, 5, {}), (2, 6, {}), (3, 8, {}), (3, 4, {}), (3, 7, {})])

我希望 T EdgeDataView 看起来像

EdgeDataView([(1, 2, {'weight':10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}),
 (3, 8, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0})])

任何想法,将不胜感激,

标签: pythongraphnodesnetworkxedges

解决方案


你可以试试networkxGraph.edge_subgraph功能

以你为例。
首先创建图表:

G = nx.DiGraph()
G.add_edges_from([(1, 2, {'weight': 10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}), 
(2, 1, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0}), (3, 8, {'weight': 0}), (3, 2, {'weight': 0}), (4, 3, {'weight': 0}), (5, 2, {'weight': 0}), (6, 2, {'weight': 0}), 
(7, 3, {'weight': 0}), (8, 3, {'weight': 0})])

接下来,选择您假装添加到新图中的节点:

edge_set = [(1, 2), (2, 3), (2, 5), (2, 6), (3, 8), (3, 4), (3, 7)]

然后,将边从一个图形提取到另一个图形:

Di_T = G.edge_subgraph(edge_set)

请注意,因为G是定向的T也将是定向的,所以:

T = Di_T.to_undirected()    # see NOTE in the end

结果

>>> T.edges(data = True)

EdgeDataView([ (1, 2, {'weight': 10}),
               (2, 3, {'weight': 0}),
               (2, 5, {'weight': 0}),
               (2, 6, {'weight': 0}),
               (3, 4, {'weight': 10}),
               (3, 7, {'weight': 0}),
               (3, 8, {'weight': 0})])

完整代码:

# example graph

G = nx.DiGraph()
G.add_edges_from([(1, 2, {'weight': 10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}), (2, 1, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0}), (3, 8, {'weight': 0}), (3, 2, {'weight': 0}), (4, 3, {'weight': 0}), (5, 2, {'weight': 0}), (6, 2, {'weight': 0}), (7, 3, {'weight': 0}), (8, 3, {'weight': 0})])


# example edge set

edge_set = [(1, 2), (2, 3), (2, 5), (2, 6), (3, 8), (3, 4), (3, 7)]


# solution

T = G.edge_subgraph(edge_set).to_undirected()
T.edges(data = True)

笔记:

通常由G.edge_subgraph(edge_set) (使用.copy)制作副本,以获得图形的新副本,而不是原始图形的引用(请参阅文档中的注释)。
但是,.to_undirected已经制作了图形的深层副本,因此无需.copy检查G.edge_subgraph.to_undirected文档以获取更多信息


推荐阅读