pandas -结合行的字符串 [英] pandas - combine strings of row

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

问题描述

我有一个像这样的数据框:

I have a dataframe like this:

    id        text
    1         DM,HTN,Enlarged prostate
    2         hypertensive and on regular treatment
    2         LBP
    3         DM,HTN,Enlarged prostate

我想像这样合并具有相同id的文本:

I want to combine the text of same id like this:

   id        text
   1         DM,HTN,Enlarged prostate
   2         hypertensive and on regular treatment LBP
   3         DM,HTN,Enlarged prostate

id 2的文本被合并. 我怎样才能做到这一点?任何帮助将不胜感激.

the texts of id 2 are combined. how can i acchieve this? Any help would be appreciated.

推荐答案

您可以使用 groupby apply 函数join.最后 reset_index :

You can use groupby and apply function join. Last reset_index:

grouped_df = df.groupby("id")['text'].apply(' '.join).reset_index()
print (grouped_df)
   id                                       text
0   1                   DM,HTN,Enlarged prostate
1   2  hypertensive and on regular treatment LBP
2   3                   DM,HTN,Enlarged prostate

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

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