首页 > 解决方案 > 熊猫如何在不丢失其他列信息的情况下进行分组

问题描述

我有这样的df

      source  destination  weight  partition
0          1            2     193          7
1          1           22    2172          7
2          2            3     188          7
3          2            1     193          7
4          2            4     403          7
...      ...          ...     ...        ...
8865    3351         3352     719          4
8866    3351         2961    6009          4
8867    3352         3351     719          4
8868    3353         1540     128          2
8869    3353         1377     198          2

这是一个图的边列表,partition是源顶点的partition信息。我想用他们的目的地分组来源以找到我试过的所有邻居

group = result.groupby("source")["destination"].apply(list).reset_index(name="neighbours")

结果是:

      source          neighbours
0          1             [2, 22]
1          2           [3, 1, 4]
2          3                 [2]
3          4          [21, 2, 5]
4          5              [4, 8]
...      ...                 ...
3348    3349  [3350, 3345, 3324]
3349    3350              [3349]
3350    3351  [2896, 3352, 2961]
3351    3352              [3351]
3352    3353        [1540, 1377]

但是在这里你可以看到我丢失了分区信息有没有办法保留这个列?

标签: pythonpandas

解决方案


如果需要按 2 列分组,请使用:

group = (result.groupby(["source", "partition"])["destination"]
               .apply(list)
               .reset_index(name="neighbours"))

如果需要通过withpartition聚合列的第一个值:GroupBy.aggfirst

group = (result.groupby("source")
               .agg({'partition':'first',"destination": list})
               .reset_index(name="neighbours"))

推荐阅读