如何使用 groupby 在 python pandas 中连接字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38127209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use groupby to concatenate strings in python pandas?
提问by user3655574
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 函数来获取另一个数据框来对数据进行分组并将单词连接成如下使用 python pandas 的格式?
Thanks
谢谢
[
[
回答by EdChum
You can apply join
on your column after groupby
:
您可以join
在以下之后申请您的专栏groupby
:
df.groupby('index')['words'].apply(','.join)
Example:
例子:
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
回答by hamx0r
If you want to save even more ink, you don't need to use .apply()
since .agg()
can take a function to apply to each group:
如果您想节省更多墨水,则无需使用,.apply()
因为.agg()
可以将一个函数应用于每个组:
df.groupby('id')['words'].agg(','.join)
df.groupby('id')['words'].agg(','.join)