首页 > 解决方案 > 如何在 Networkx 中将两个 egdes 和节点合并为一个具有共同起始节点的节点?

问题描述

我是 networkx 的新手,我正在向 Stackeroverflow 社区寻求帮助。

我正在尝试组合具有共同起始节点的节点和边,如下图所示。箭头显示预期结果。

意大利特鲁利

nodes_to_combine = [n for n in graph.nodes if len(list(graph.neighbors(n))) == 2]
for node in nodes_to_combine:
    graph.add_edge(*graph.neighbors(node))
nx.draw(graph, with_labels=True)

谁能帮我弄清楚这个?

标签: pythonnetworkx

解决方案


NetworkX 没有合并图中节点的功能,因此应该手动实现。这是没有属性合并的示例(它可以有自己的逻辑):

def merge(G, n1, n2):
    # Get all predecessors and successors of two nodes
    pre = set(G.predecessors(n1)) | set(G.predecessors(n2))
    suc = set(G.successors(n1)) | set(G.successors(n2))
    # Create the new node with combined name
    name = str(n1) + '/' + str(n2)
    # Add predecessors and successors edges
    # We have DiGraph so there should be one edge per nodes pair
    G.add_edges_from([(p, name) for p in pre])
    G.add_edges_from([(name, s) for s in suc])
    # Remove old nodes
    G.remove_nodes_from([n1, n2])

下面是它的工作原理:

import networkx as nx

G = nx.DiGraph()
G.add_edges_from([
    ('0','20'),
    ('10','20'),
    ('10','30'),
    ('20','40'),
    ('30','50'),
])
nx.draw(
    G,
    pos=nx.nx_agraph.graphviz_layout(G, prog='dot'),
    node_color='#FF0000',
    with_labels=True
)

在此处输入图像描述

merge(G, '20', '30')
nx.draw(
    G,
    pos=nx.nx_agraph.graphviz_layout(G, prog='dot'),
    node_color='#FF0000',
    with_labels=True
)

在此处输入图像描述


推荐阅读