【问题标题】:pandas groupby() with custom aggregate function to concatenate columns then rows using pandas带有自定义聚合函数的 pandas groupby() 使用 pandas 连接列和行
【发布时间】:2020-10-05 14:21:12
【问题描述】:

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

 Column1    Column2    Column3    Column4
 1          I          am         abc
 3          on         weekend    holidays
 1          I          do         business
 2          I          am         xyz
 3          I          do         nothing
 2          I          do         job

使用 pandas 应用 groupby() 后,预期结果是:

Column1    Column2
1          I am abc I do business
2          I am Xyz I do job
3          On weekend holidays I do nothing

所需的聚合首先适用于列而不是行。

如何执行?

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    你试过了吗:

    df['newcol'] = df.apply(lambda x: " ".join(x[1:]), axis=1)
    df.groupby('Column1').agg({'newcol': lambda x: " ".join()})
    

    【讨论】:

      【解决方案2】:

      首先使用DataFrame.set_indexDataFrame.stack,然后在GroupBy.agg 中聚合join

      df1 = (df.set_index('Column1')
               .stack()
               .groupby("Column1")
               .agg(' '.join)
               .reset_index(name='Column2'))
      print (df1)
         Column1                           Column2
      0        1            I am abc I do business
      1        2                 I am xyz I do job
      2        3  on weekend holidays I do nothing
      

      【讨论】:

        【解决方案3】:

        你可以试试这个吗?首先将你想要的列的单词组合成新列,然后使用groupby 将它们连接在一起。

        df['new_col'] = df['Column2'] + str(" ") + df['Column3'] + str(" ") + df['Column4']

        df.groupby('Column1')['new_col'].agg(lambda x: ' '.join(x.astype(str)))

        Column1
        1              I am abc I do business
        2                   I am xyz I do job
        3    on weekend holidays I do nothing
        Name: new_col, dtype: object
        

        【讨论】:

          【解决方案4】:

          你可以试试如下

          def apply_union(x):
              ## join multiple columns to single sting in row
              x = x.apply(lambda row: ' '.join(row.values.astype(str)), axis=1)
              ## concat rows to single string
              x = x.str.cat(sep=" ")
              return x
          df.groupby("Column1")[["Column2","Column3","Column4"]].apply(lambda x: apply_union(x))
          

          【讨论】:

            【解决方案5】:

            您可以利用最后三列是字符串类型的事实并将它们组合起来,使用sum 函数和 column1 上的 groupby,这次使用 python 的 string join 函数进行聚合:

            outcome = (df
                       .set_index("Column1")
                       #this helps to put space between
                       #the columns when summed
                       .add(' ')
                       #this combines the columns into one
                       .sum(axis=1)
                       .str.rstrip(" ")
                       .groupby("Column1")
                       .agg(" ".join)
                       .reset_index(name='Column2')
                      )
            
            outcome
            
                Column1      Column2
            0   1           I am abc I do business
            1   2           I am xyz I do job
            2   3           on weekend holidays I do nothing
            

            【讨论】:

              猜你喜欢
              • 2019-06-08
              • 2017-08-04
              • 2023-01-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-11-05
              • 2021-11-01
              • 2015-07-04
              相关资源
              最近更新 更多