Extracting connected components 1 - 100

24 views
Skip to first unread message

Curtis Hampton

unread,
Aug 21, 2014, 10:02:05 PM8/21/14
to networkx...@googlegroups.com
I have a network that has a bunch of connected components, and I would like to extract the first 100 connected components into a new graph.  I know how to extract individual connected components and union the individual connected components together into a new graph.

However, I know there must be a better way then extract all 100 connected components and union-ing all these together.

# create empty graph
G = nx.Graph()

# add edges to graph representing disconnected components

G.add_edges_from([('a','b'),('b','c'),('a','c'),('d','e'),('d','f'),('d','g'),('h','j'),('j','k'),('h','k'),('m','n'),('n','o'),('o','p'),('p','m'),('n','p')])

# extract individual components (I would like a more efficient way to do this for the first 100 components)
G0 = nx.connected_component_subgraph(G)[0]
G1 = nx.connected_component_subgraph(G)[1]
G2 = nx.connected_component_subgraph(G)[2]
...
(with the actual network, I would like to extract the first 100 connected components and this is inefficient)


# union connected components together into a new graph

G_union = nx.union([G0,G1,G2,...])

Daniel Schult

unread,
Aug 21, 2014, 11:36:02 PM8/21/14
to networkx...@googlegroups.com
nx.connected_components(G) returns a generator of lists of nodes--one list for each connected component. By taking the union of node-lists instead of union of subgraphs you should save time.

Something like this (untested):

import itertools
ccs = nx.connected_components(G)   # this returns a generator
nodes=set()
nodes.update( *itertools.islice(ccs, 100) )  # islice gets the first 100; 
G_union = G.subgraph( nodes )


--
You received this message because you are subscribed to the Google Groups "networkx-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to networkx-discu...@googlegroups.com.
To post to this group, send email to networkx...@googlegroups.com.
Visit this group at http://groups.google.com/group/networkx-discuss.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages