【问题标题】:How to contract nodes that have only 2 edges in NetworkX?如何在 NetworkX 中收缩只有 2 条边的节点?
【发布时间】:2019-06-14 14:57:32
【问题描述】:

我在 NetworkX 中有一个图表,大致是这样的:

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

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

a---b---d
    |
    f

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

【问题讨论】:

标签: python graph networkx


【解决方案1】:

@zohar.kom 更简洁的版本是使用 subgraph 方法:

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)

【讨论】:

  • 1.我假设您的意思是[node for node in graph.nodes() if graph.degree(node) != threshold],否则我们将只删除节点,而不是我们真正想要的节点。 2. 这还不够,因为你只删除了相关的节点,这很好,但你还需要添加边。例如,原始示例中的边 (b,f) 在此实现中将丢失。
  • 啊读得不够正确。你是对的,那么这种方法有点毫无意义。感谢您指出。
【解决方案2】:

可以这样做:

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)

【讨论】:

    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2016-04-12
    • 2016-07-04
    相关资源
    最近更新 更多