pandas groupby串联多个列中的字符串 [英] pandas groupby concatenate strings in multiple columns

查看:107
本文介绍了 pandas groupby串联多个列中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个熊猫数据框:

I have this pandas data frame:

df = DataFrame({'id':['a','b','b','b','c','c'], 'category':['z','z','x','y','y','y'], 'category2':['1','2','2','2','1','2']})

看起来像:

which looks like:

  category category2 id
0        z         1  a
1        z         2  b
2        x         2  b
3        y         2  b
4        y         1  c
5        y         2  c

我想要做的是对groupby id进行分组,并将其他两列作为唯一字符串的串联返回。

What i'd like to do is to groupby id and return the other two columns as a concatenation of unique strings.

结果如下:

The outcome would look like:

  category category2 id
0        z         1  a
1      zxy         2  b
2        y        12  c


推荐答案

使用 groupby / agg 来聚合组。对于每个组,应用 set 来查找唯一的字符串,并使用''join 来连接字符串:

Use groupby/agg to aggregate the groups. For each group, apply set to find the unique strings, and ''.join to concatenate the strings:

In [34]: df.groupby('id').agg(lambda x: ''.join(set(x)))
Out[34]: 
   category category2
id                   
a         z         1
b       yxz         2
c         y        12

要将索引中的 id 移至生成的DataFrame的一列,请调用 reset_index

To move id from the index to a column of the resultant DataFrame, call reset_index:

In [59]: df.groupby('id').agg(lambda x: ''.join(set(x))).reset_index()
Out[59]: 
  id category category2
0  a        z         1
1  b      yxz         2
2  c        y        12

这篇关于 pandas groupby串联多个列中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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