七度猫 2021-04-21 20:58 采纳率: 100%
浏览 85
已采纳

如何利用python将字符串聚合到一个文本

我想要把这个表格按照酒店名称和入住房型做聚类,去掉评论日期,把评论详情合并到一起。我利用pandas的聚合处理只能算出每个聚类有多少条评论。各位大神有什么方法么?

  • 写回答

3条回答 默认 最新

  • CSDN专家-HGJ 2021-04-21 21:40
    关注

    给你一个示例代码参考一下,结合自己的数据结构和处理要求作进一步调整。

    import pandas as pd 
    
    df=pd.DataFrame({'hotel':['h1','h1','h3','h2','h3','h1'],'comments':['nice','better services ','not good','wonderful','it\'s ok','friendly people, beautiful place'],'type':['business','single','ordinary','single','business','ordinary']})
    
    df1=df.groupby(['hotel','type'])['comments'].agg(lambda x: '\n'.join(x))
    print(df1)
    
    #output:
    
    hotel  type    
    h1     business                                nice
           ordinary    friendly people, beautiful place
           single                      better services
    h2     single                             wonderful
    h3     business                             it's ok
           ordinary                            not good
    Name: comments, dtype: object
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?