从 Pandas 数据框中的一组对中获取所有连接的组件

Sus*_*ant 3 python pandas

我有一个数据框,其中一列作为对,另一列作为键。我想创建一组链接索引链:

       match1  match2
0          12       5
1          34      12
2          18      29
3          69      31
4          33      34
5.         15     69
Run Code Online (Sandbox Code Playgroud)

我想得到一个输出,将所有连接的组件链接到列表中,可能是这样的:

[12,5,34,33], [18,29], [69, 31, 15]
Run Code Online (Sandbox Code Playgroud)

编辑:我之前试过这个。

        rev_matches = df[['match1', 'match2']]
        rev_matches['match_list'] = rev_matches.values.tolist()
        rev_matches = rev_matches[['match_list']]
        rev_matches['Key'] = rev_matches.index
        rev_matches = rev_matches.explode('match_list')
        G = nx.from_pandas_edgelist(rev_matches, 'match_list', 'Key')
        l = list(nx.connected_components(G))
Run Code Online (Sandbox Code Playgroud)

现在这也没有奏效。建立的联系不准确。有人也可以解释我这错在哪里。谢谢

ank*_*_91 5

这看起来像 networkx:

import networkx as nx
G = nx.Graph()
G.add_edges_from(df[['match1','match2']].to_numpy().tolist())
print(list(nx.connected_components(G)))
#[{5, 12, 33, 34}, {18, 29}, {15, 31, 69}]
Run Code Online (Sandbox Code Playgroud)