python - 熊猫如何在不丢失其他列信息的情况下进行分组
问题描述
我有这样的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]
但是在这里你可以看到我丢失了分区信息有没有办法保留这个列?
解决方案
如果需要按 2 列分组,请使用:
group = (result.groupby(["source", "partition"])["destination"]
.apply(list)
.reset_index(name="neighbours"))
如果需要通过withpartition
聚合列的第一个值:GroupBy.agg
first
group = (result.groupby("source")
.agg({'partition':'first',"destination": list})
.reset_index(name="neighbours"))
推荐阅读
- verilog - 从 VC709 fpga 板上的差分板载时钟创建单端时钟
- c# - json反序列化以选择类
- php - Laravel Eloquent 如果变量存在查询它
- python - 为什么嵌套列表会在 Ubuntu 14.04 上泄漏内存?
- graphql - GrahpQL:使用多个可选参数创建请求
- cassandra - Cassandra 中的阅读一致性级别
- meteor - 流星中的 Template.currentData() 到底有什么用?
- javascript - 读取传入的流式响应
- javascript - 'res.location(path)' 什么都不做?(表达)
- python - 如何在每次迭代中打印出名称/标签