Separate 'networks' in a panda's dataframe

Viewed 51

Given the following df:

 first  second
0     a       3
1     b       5
2     a       2
3     e       9
4     c       2
5     d       7
6     d       8
7     c       5

I would like to separate the distinct 'networks' into their own dataframes. So e.g. a goes to 2, but 2 is also linked to c, which is also linked to 5, etc. meaning they form a network.

This means you should end up with the following three dataframes:

 first  second
0     a       3
1     b       5
2     a       2
3     c       5
4     c       2

  first  second
0     d       7
1     d       8

  first  second
0     e       9

Is there an easy way to do this, and is there a way to generalise to any number of columns?

Thanks!

1 Answers

We can use connected_components from networkx to subset the dataframe

import networkx as nx

G = nx.from_pandas_edgelist(df, 'first', 'second')
[df.query('first in @cc') for cc in nx.connected_components(G)]

[  first  second
 0     a       3
 1     b       5
 2     a       2
 4     c       2
 7     c       5,
   first  second
 3     e       9,
   first  second
 5     d       7
 6     d       8]
Related