使用 Networkx 返回网络中未连接的节点岛

lon*_*n11 1 python isolation networkx

我正在使用 NetworkX 来分析传输连接的网络 G。经过可视化后,我发现有一些节点“孤岛”与网络没有任何连接。这些岛屿大多由 2 到 5 个节点组成。由于网络非常大,我正在寻找一个返回每个岛的命令,最好是在指示节点名称的数据结构中。该isolates(G)命令仅返回零度节点,但我对岛屿感兴趣。有这样的命令吗?

小智 5

看看connected_components函数

# Create three separate graphs and then compose them together.
import networkx as nx
G = nx.complete_graph(8)
G2 = nx.complete_graph(range(13, 15))
G3 = nx.complete_graph(range(16, 19))

G = nx.compose_all([G, G2, G3])
nx.draw(G)
Run Code Online (Sandbox Code Playgroud)

图表

使用connected_components()

list(nx.connected_components(G))
Run Code Online (Sandbox Code Playgroud)
[{0, 1, 2, 3, 4, 5, 6, 7}, {13, 14}, {16, 17, 18}]
Run Code Online (Sandbox Code Playgroud)
threshold = 6
[c for c in nx.connected_components(G) if len(c) < threshold]
Run Code Online (Sandbox Code Playgroud)
[{13, 14}, {16, 17, 18}]
Run Code Online (Sandbox Code Playgroud)

您还可以查看connected_components_subgraph