首页 > 解决方案 > 使用列的唯一值作为索引对数据框进行分组

问题描述

按值对数据帧索引的不同值进行分组或堆叠的最有效方法是什么?

这个df:

color   alert

blue    A
blue    B
red     A
green   C

到:

color   alert

blue    [A, B]
red     A
green   C

标签: pythonpandas

解决方案


您需要 agroupby和聚合成 a list

df.groupby('color').alert.agg(list).reset_index()

   color   alert
0   blue  [A, B]
1  green     [C]
2    red     [A]

推荐阅读