且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Pandas:根据另一列中的值对两列进行分组

更新时间:2022-12-09 21:58:41

使用 groupbyagg 通过带有 tolist 的自定义函数:

Use groupby and agg by custom function with tolist:

df = df.groupby('id').agg(lambda x: x.tolist())
print (df)
              name          color
id                               
id_1  [alex, sara]  [blue, black]
id_2  [james, aly]  [yellow, red]
id_4   [dave, lin]   [pink, grey]