Pandas:根据另一列中的值对两列进行分组 [英] Pandas: Group two columns based on value in another column

查看:71
本文介绍了Pandas:根据另一列中的值对两列进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python/pandas 很陌生,我有一个看起来像这样的数据框:

I'm pretty new to python/pandas and I have a dataframe that looks something like this:

 id         name        color
id_1        alex        blue
id_2        james       yellow
id_1        sara        black
id_4        dave        pink
id_4        lin         grey
id_2        aly         red

我想按 id 分组并将其他两列中的值作为列表获取:

I want to group by id and get the values in the other two columns as a list:

  id           name              color
id_1        [alex,sara]       [blue,black]
id_2        [james,aly]       [yellow,red]
id_4        [dave,lin]        [pink,grey]

有没有简单的方法来做到这一点?

Is there an easy way to do that?

推荐答案

使用 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]

这篇关于Pandas:根据另一列中的值对两列进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆