删除孤立的节点以使图形连接

Removing isolated nodes in order to make the graph connected

我有一个未连接的图表。

import json
import networkx as nx
from networkx.readwrite import json_graph

G = nx.read_gml('/Users/luca/Desktop/networks_analysis/astro-ph/astro-ph.gml')

print(nx.info(G))
Name: 
Type: Graph
Number of nodes: 16706
Number of edges: 121251
Average degree:  14.5159

nx.is_connected(G)
False

我试图删除所有孤立的节点,但图形仍然没有连接。

G.remove_nodes_from(list(nx.isolates(G)))

print(nx.info(G))
Name: 
Type: Graph
Number of nodes: 16046
Number of edges: 121251
Average degree:  15.1129

nx.is_connected(G)
False

如何获得连通图? 谢谢。

你可以得到最大的连通子图:

nodes = max(nx.connected_components(G), key=len)
H = nx.subgraph(G, nodes)