分组多列并使用dask进行聚合

时间:2019-11-29 13:05:51

标签: python pandas dataframe pandas-groupby dask

黄昏数据框如下:

A     B     C     D
1     foo   xx    this
1     foo   xx    belongs
1     foo   xx    together
4     bar   xx    blubb

我想按A,B,C列分组,然后将D中的字符串连接起来,中间用空格隔开,以获得

A     B     C     D
1     foo   xx    this belongs together
4     bar   xx    blubb

我知道如何用熊猫来做到这一点:

df_grouped = df.groupby(['A','B','C'])['D'].agg(' '.join).reset_index()

如何借助dask来实现?

2 个答案:

答案 0 :(得分:1)

ddf = ddf.groupby(['A','B','C'])['D'].apply(lambda row: ' '.join(row)).reset_index()
ddf.compute()

输出:

Out[75]: 
   A    B   C                      D
0  1  foo  xx  this belongs together
0  4  bar  xx                  blubb

答案 1 :(得分:0)

您可以使用CustomAggregation,其中每块和聚合操作都是您的' '.join方法。

https://docs.dask.org/en/latest/dataframe-api.html#custom-aggregation