【发布时间】:2019-06-14 14:57:32
【问题描述】:
我在 NetworkX 中有一个图表,大致是这样的:
a---b---c---d
|
e---f
我想简化它,删除只有 2 条边的中间节点。
a---b---d
|
f
如何在 NetworkX 中做到这一点?我只看到删除节点方法或收缩边缘。但这与节点有关。
【问题讨论】:
我在 NetworkX 中有一个图表,大致是这样的:
a---b---c---d
|
e---f
我想简化它,删除只有 2 条边的中间节点。
a---b---d
|
f
如何在 NetworkX 中做到这一点?我只看到删除节点方法或收缩边缘。但这与节点有关。
【问题讨论】:
@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)
【讨论】:
[node for node in graph.nodes() if graph.degree(node) != threshold],否则我们将只删除节点,而不是我们真正想要的节点。 2. 这还不够,因为你只删除了相关的节点,这很好,但你还需要添加边。例如,原始示例中的边 (b,f) 在此实现中将丢失。
可以这样做:
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)
【讨论】: