如何使用groupby连接python pandas中的字符串? [英] How to use groupby to concatenate strings in python pandas?

查看:163
本文介绍了如何使用groupby连接python pandas中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在顶部有数据框.有没有一种方法可以使用groupby函数来获取另一个数据帧来对数据进行分组,并将单词连接成类似下面使用python pandas的格式?

I currently have dataframe at the top. Is there a way to use a groupby function to get another dataframe to group the data and concatenate the words into the format like further below using python pandas?

谢谢

[

推荐答案

您可以在groupby之后在列上应用join:

You can apply join on your column after groupby:

df.groupby('index')['words'].apply(','.join)

示例:

In [326]:
df = pd.DataFrame({'id':['a','a','b','c','c'], 'words':['asd','rtr','s','rrtttt','dsfd']})
df

Out[326]:
  id   words
0  a     asd
1  a     rtr
2  b       s
3  c  rrtttt
4  c    dsfd

In [327]:
df.groupby('id')['words'].apply(','.join)

Out[327]:
id
a        asd,rtr
b              s
c    rrtttt,dsfd
Name: words, dtype: object

这篇关于如何使用groupby连接python pandas中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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