[译] 对dataframe数据按照某列值进行分组,分组后连接字符串

In[38]:
df.groupby(['name','month'])['text'].apply(','.join).reset_index()

Out[38]: 
    name  month         text
0  name1     11           du
1  name1     12        aj,oj
2  name2     11     fin,katt
3  name2     12  mycket,lite
  • groupby 进行分组
  • [‘name’, 'month']是分组的字段
  • [‘text’]是需要连接的列名
  • apply对text应用对应的处理函数
  • reset_index 合并之后需要重新重置index

参考来源:
https://stackoverflow.com/questions/27298178/concatenate-strings-from-several-rows-using-pandas-groupby

作者: everfight
欢迎转载
原文地址:https://www.cnblogs.com/everfight/p/concatenate-strings-from-several-rows-using-pandas-groupby.html