【问题标题】:How to merge rows in dataframe with different columns?如何将数据框中的行与不同的列合并?
【发布时间】:2019-06-25 05:27:43
【问题描述】:

我想将数据帧的行与一个公共列值合并,然后合并以逗号分隔的其余列值以获得字符串值,并转换为数组/列表以获得 int 值。

A   B     C    D
1  one   100  value
4  four  400  value
5  five  500  value
2  two   200  value

预期结果如下:

   A                B                 C            D
[1,4,5,2]  one,four,five,two  [100,400,500,200]  value

我可以将 groupby 用于 D 列,但我如何一次将 apply(np.array) 和 apply(','.join) 用于 df 中的 B 列?

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    动态解决方案 - 将字符串列连接起来,将数字转换为带有GroupBy.agg 的列表:

    f = lambda x: x.tolist() if np.issubdtype(x.dtype, np.number) else ','.join(x)
    #similar for test strings - https://stackoverflow.com/a/37727662
    #f = lambda x: ','.join(x) if np.issubdtype(x.dtype, np.flexible) else x.tolist()
    df1 = df.groupby('D').agg(f).reset_index().reindex(columns=df.columns)
    print (df1)
                  A                  B                     C      D
    0  [1, 4, 5, 2]  one,four,five,two  [100, 400, 500, 200]  value
    

    另一种解决方案是为每一列分别指定每个函数:

    df2 = (df.groupby('D')
            .agg({'A': lambda x: x.tolist(), 'B': ','.join, 'C':lambda x: x.tolist()})
            .reset_index()
            .reindex(columns=df.columns))
    
    print (df2)
    
                  A                  B                     C      D
    0  [1, 4, 5, 2]  one,four,five,two  [100, 400, 500, 200]  value
    

    【讨论】:

      【解决方案2】:
      df = df.groupby('D').apply(lambda x: pd.Series([list(x.A),','.join(x.B),list(x.C)])).reset_index().rename({0:'A',1:'B',2:'C'}, axis=1)
      
      df = df[['A','B','C','D']]
      

      输出

                    A                  B                     C      D
      0  [1, 4, 5, 2]  one,four,five,two  [100, 400, 500, 200]  value
      

      【讨论】:

        【解决方案3】:

        为什么不单线agg

        >>> df.groupby('D', as_index=False).agg(lambda x: x.tolist() if x.dtype != object else ','.join(x))[df.columns]
                      A                  B                     C      D
        0  [1, 4, 5, 2]  one,four,five,two  [100, 400, 500, 200]  value
        >>> 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-10
          • 1970-01-01
          • 2020-05-04
          相关资源
          最近更新 更多