【问题标题】:How to group by one column or another in pandas如何在熊猫中按一列或另一列分组
【发布时间】:2022-11-10 11:01:01
【问题描述】:

我有一张像这样的桌子:

    col1    col2
0   1       a
1   2       b
2   2       c
3   3       c
4   4       d

如果行在col1 中具有匹配值,我希望将它们组合在一起或者col2。也就是说,我想要这样的东西:

> (
    df
    .groupby(set('col1', 'col2'))  # Made-up syntax
    .ngroup())
0  0
1  1
2  1
3  1
4  2

有没有办法用熊猫做到这一点?

【问题讨论】:

    标签: pandas group-by networkx graph-theory


    【解决方案1】:

    仅使用 pandas 就不容易做到这一点。实际上,当第二组中的两个项目连接时,两个相距较远的组可以连接起来。

    您可以使用图论来解决这个问题。使用由两个(或更多)组形成的边找到连接的组件。一个python库是networkx

    import networkx as nx
    
    g1 = df.groupby('col1').ngroup()
    g2 = 'a'+df.groupby('col2').ngroup().astype(str)
    
    # make graph and get connected components to form a mapping dictionary
    G = nx.from_edgelist(zip(g1, g2))
    d = {k:v for v,s in enumerate(nx.connected_components(G)) for k in s}
    
    # find common group
    group = g1.map(d)
    
    df.groupby(group).ngroup()
    

    输出:

    0    0
    1    1
    2    1
    3    1
    4    2
    dtype: int64
    

    图形:

    【讨论】:

    • 请注意,如果您在 col1 中有 NaN,请添加 G.remove_node(-1) 以删除 ngroup 默认值并将 g1.map(d) 更改为 g1.map(d).fillna(g2.map(d))
    猜你喜欢
    • 2022-07-14
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2016-07-07
    • 2020-06-11
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多