代码之家  ›  专栏  ›  技术社区  ›  culebrón

如何收缩NetworkX中只有2个边的节点?

  •  2
  • culebrón  · 技术社区  · 6 年前

    我在NetworkX中有一个大致如下的图:

    a---b---c---d
        |
        e---f
    

    我想简化它,删除只有2条边的中间节点。

    a---b---d
        |
        f
    

    如何在NetworkX中实现这一点?我只看到移除节点方法或收缩边。但这与节点有关。

    2 回复  |  直到 6 年前
        1
  •  2
  •   zohar.kom    6 年前

    可以这样做:

    for node in list(G.nodes()):
        if G.degree(node) == 2:
            edges = list(G.edges(node))
            G.add_edge(edges[0][1], edges[1][1])
            G.remove_node(node)
    
        2
  •  0
  •   cvanelteren    6 年前

    @zohar.kom的更清晰版本将使用子图方法:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    graph = nx.random_graphs.watts_strogatz_graph(100, 3, .4)
    
    threshold = 2
    sub       = graph.subgraph([node for node in graph.nodes() if \
                                graph.degree(node) != threshold])
    
    fig, ax = plt.subplots(2, 1)
    
    nx.draw(graph, ax = ax[0], with_labels = 1)
    nx.draw(sub, ax = ax[1], with_labels = 1)
    

    enter image description here