使用Networkx从连接的组件创建团体 [英] Creating cliques from connected components using networkx

查看:115
本文介绍了使用Networkx从连接的组件创建团体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Python中的networkx创建了一个图形.

I have created a graph using networkx in Python.

import networkx as nx
G = createGraph ('abc.csv') #My function that returns graph from file.

connected_components = nx.connected_components(G)
print (connected_components)
<generator object connected_components at 0x00000000221EF1A8>

nbr_cc = nx.number_connected_components(G)
print (nbr_cc)
57215

我想将每个连接的组件转换成一个小集团,然后以以下方式编写一个csv文件:

I want to convert every connected component into a clique and then write a csv file in following manner:

node1_id    node2_id    connected_component_id
1           2           1
1           3           1
1           4           1
2           1           1
.           .           .
.           .           .
500         600         9

该怎么做?有什么方法可以在notworkx或其他任何python库中实现这一目标?

How to do that? Is there any way to achieve that in notworkx or using any other python library?

推荐答案

您可以使用itertools.permutations:

>>> G
<networkx.classes.graph.Graph object at 0x7f123559f3c8>
>>> list(nx.connected_components(G))
[{0, 4, 5, 6, 7, 9}, {1}, {8, 2}, {3}]

>>> import itertools
>>> import csv
>>>
>>> with open('cliques.csv', 'tw') as f:
...     w = csv.writer(f, csv.excel_tab)
...     w.writerow(['node1', 'node2', 'clique'])
...     w.writerows(p + (i,) for i, n in enumerate(nx.connected_components(G), 1) for p in itertools.permutations(n, 2))
... 
20

创建一个包含以下内容的文件:

Creates a file containing:

node1   node2   clique
0       4       1
0       5       1
0       6       1
0       7       1
0       9       1
4       0       1
4       5       1

...

9       6       1
9       7       1
8       2       3
2       8       3

这篇关于使用Networkx从连接的组件创建团体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆