如何在Python中使用networkx获取最大(未连接)的网络/集群?

时间:2018-05-02 10:03:48

标签: python python-3.x networkx

我有以下示例数据:

my_network_data = [(39, 118), (179, 14), (35, 118), (225, 14), (64, 118), (6, 14), (187, 14), (161, 14), (42, 14), (53, 14), (47, 1), (127, 14), (14, 118), (3, 1), (175, 14), (21, 118), (5, 14), (18, 14), (122, 1), (137, 14), (157, 14), (19, 14), (19, 118), (118, 14), (30, 118), (159, 14), (124, 118), (56, 14), (161, 118), (100, 14), (53, 118), (136, 118), (41, 14), (4, 14), (217, 14), (32, 14), (175, 118), (104, 14), (82, 118), (4, 118), (222, 14), (201, 118), (136, 14), (86, 1), (153, 14), (195, 14)]

如果我使用networkx绘制它,我会执行以下操作:

import networkx as nx
g = nx.Graph()
g.add_edges_from(my_network_data)   
print(nx.info(g))

输出:

Name: 
Type: Graph
Number of nodes: 41
Number of edges: 45
Average degree:   2.1951

图表如下所示:

nx.draw(g, with_labels=True)

enter image description here

如何使用networkx获取有2个不同群集以及哪些群集在这些群集中的信息?

建议输出:

[[1, 86, 47, 3, 122], [14, 118, 136, 53, 179, 30, 100, 41, 35, 4, 19, 82, 104, 159, 64, 32, 124, 14, 39, 4, 137, 136, 187, 217, 153, 5, 53, 19, 42, 175, 18, 21, 222, 175, 6, 195, 56, 157, 201, 161, 161, 127,  225]]

我不确定networkx是否是此任务的最佳库。如果您有更好的建议(使用Python),我愿意使用它。

1 个答案:

答案 0 :(得分:1)

看起来nx.connected_components()就是您所需要的:

for c in nx.connected_components(g):
    print(c)
{4, 5, 6, 136, 137, 14, 18, 19, 21, 153, 157, 30, 159, 32, 161, 35, 39, 41, 42, 175, 179, 53, 56, 187, 64, 195, 201, 82, 217, 222, 225, 100, 104, 118, 124, 127}
{1, 3, 47, 86, 122}