簡體   English   中英

使用Networkx從連接的組件創建團體

[英]Creating cliques from connected components using networkx

我已經在Python使用networkx創建了一個圖。

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文件:

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

怎么做? 有什么方法可以在notworkx或其他任何python庫中實現這一目標嗎?

您可以使用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

創建一個包含以下內容的文件:

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中編碼的,該答案實際上與PaulPanzer的答案相同:

G=nx.Graph()
G.add_edges_from([(1,2), (2,3), (4,5), (5,6)])
list(nx.connected_components(G))
> [{1,2,3},{4,5,6}]

#we're done setting G up.  Let's do it.

CCs = nx.connected_components(G)
complete_subgraphs = (nx.complete_graph(component) for component in CCs)
H=nx.compose_all(complete_subgraphs)

在這里,我們首先找到連接的組件(從技術上講,我們為它們創建一個生成器)。 然后,我們使用nx.complete_graph(nodes)為每個組件找到所有完整的圖。 最后,我們將所有圖與compose_all結合在一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM