Merging rows in a dataframe based on reoccurring values

Viewed 46

I have the following dataframe with each row containing two values.

print(x)

        
0    0   1
1    4   5
2    8   9
3   10  11
4   14  15
5   16  17
6   16  18
7   16  19
8   17  18
9   17  19
10  18  19
11  20  21

I want to merge these values if one or both values of a particular row reoccur in another row. The principal can be explained as follows: if A and B are together in one row and B and C are together in another row, then it means that A, B and C should be together. What I want as an outcome looking at the dataframe above is:

0    0   1
1    4   5
2    8   9
3   10  11
4   14  15
5   16  17 18 19
6   20  21

I tried creating a loop with df.duplicated that would create such an outcome, but it hasn't worked out yet.

1 Answers

This seems like graph theory problem dealing with connected components. You can use the networkx library:

import networkx as nx
g = nx.from_pandas_edgelist(df, 'a', 'b')

pd.concat([pd.Series([list(i)[0], 
                      ' '.join(map(str, list(i)[1:]))],
                    index=['a', 'b']) 
           for i in list(nx.connected_components(g))], axis=1).T

Output:

    a         b
0   0         1
1   4         5
2   8         9
3  10        11
4  14        15
5  16  17 18 19
6  20        21
Related