【问题标题】:Aggregate and concatenate multiple columns聚合和连接多列
【发布时间】:2022-11-30 18:16:53
【问题描述】:

我想对我的数据框进行分组并将其他列的值/字符串连接在一起。

   Year Letter  Number  Note   Text
0  2022      a       1     8     hi
1  2022      b       1     7  hello
2  2022      a       1     6    bye
3  2022      b       3     5    joe

对此:

             Column
Year Letter              
2022 a            1|8|hi; 1|6|bye
     b            1|7|hello; 3|5|joe

我用 groupby、apply() 和 agg() 尝试了一些东西,但我无法让它工作:

df.groupby(['Year', 'Letter']).agg(lambda x: '|'.join(x))

输出:

                  Text
Year Letter           
2022 a          hi|bye
     b       hello|joe

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    利用:

    df = (df.assign(Text= df[['Number','Note','Text']].astype(str).agg('|'.join, axis=1))
             .groupby(['Year', 'Letter'])['Text']
             .agg('; '.join)
             .to_frame())
    print (df)
                               Text
    Year Letter                    
    2022 a          1|8|hi; 1|6|bye
         b       1|7|hello; 3|5|joe
    

    或者:

    f = lambda x:  '; '.join('|'.join(y) for y in x.astype(str).to_numpy())
    df = (df.groupby(['Year', 'Letter'])[['Number','Note','Text']].apply(f)
            .to_frame(name='Text')
             )
    print (df)
                               Text
    Year Letter                    
    2022 a          1|8|hi; 1|6|bye
         b       1|7|hello; 3|5|joe
    

    【讨论】:

      【解决方案2】:

      使用groupby.apply

      cols = ['Year', 'Letter']
      (df.groupby(cols)
         .apply(lambda d: '; '.join(d.drop(columns=cols) # or slice the columns here
                                     .astype(str)
                                     .agg('|'.join, axis=1)))
         .to_frame(name='Column')
      )
      

      输出:

                               Column
      Year Letter                     
      2022 a          1|8|hi; 1|6|bye
           b       1|7|hello; 3|5|joe
      

      【讨论】:

        猜你喜欢
        • 2017-11-17
        • 1970-01-01
        • 2019-08-29
        • 1970-01-01
        • 1970-01-01
        • 2023-02-03
        • 1970-01-01
        • 2011-09-23
        • 1970-01-01
        相关资源
        最近更新 更多