熊猫“滚动” groupby

Binyamin Even

假设这是我的df:

    group     connected_to
0     1              1
1     2              0
2     2              1
3     2              2
4     3              5
5     4              4
6     3              7 
7     5              5

我想得到的是minimal group per connected rows

因此,行0连接到1,因此它们在同一组中。第2行也连接到1-因此它加入了组。第3行连接到加入该组的第2行,因此它也加入该组等。第4行未连接到第一个组中的任何行,因此它是新组。输出应如下所示:

    group     connected_to   minimal_group
0     1              1            1
1     2              0            1
2     2              1            1
3     2              2            1
4     3              5            3
5     4              4            3
6     3              7            3 
7     5              5            3

我实现它使用for内部的while-真正丑陋的解决方案。在熊猫上有没有更优雅的方法?

耶斯列尔

采用:

import networkx as nx

#convert index to column index
df1 = df.reset_index()

# Create the graph from the dataframe
g = nx.Graph()
g = nx.from_pandas_edgelist(df1,'index','connected_to')

connected_components = nx.connected_components(g)

# Find the component id of the nodes
node2id = {}
for cid, component in enumerate(connected_components):
    for node in component:
        node2id[node] = cid

mapping index column by connected groups and get minimal group to new column
df['minimal_group'] = df1.groupby(df1['index'].map(node2id))['group'].transform('min')
print (df)
   group  connected_to  minimal_group
0      1             1              1
1      2             0              1
2      2             1              1
3      2             2              1
4      3             5              3
5      4             4              3
6      3             7              3
7      5             5              3

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章