Dask:Dataframe groupBy上的nunique方法

时间:2017-08-28 15:51:01

标签: python dask dask-distributed

我想知道在使用Dask进行groupBy聚合之后是否可以获得给定列中的唯一项目数。我在文档中看不到这样的内容。它在pandas数据帧上可用,非常有用。我已经看到了与此相关的一些问题,但我不确定它是否已实施。

有人可以给我一些暗示吗?

3 个答案:

答案 0 :(得分:2)

要在this comment上进行扩展,您可以直接在SeriesGroupBy上使用O(1) | O(log(n))

nunique

有关更多讨论,请参见https://github.com/dask/dask/issues/6280

答案 1 :(得分:1)

请参阅:

Constructing Mode and Corresponding Count Functions Using Custom Aggregation Functions for GroupBy in Dask

从源代码看起来你可以在agg之外做nunique。

答案 2 :(得分:1)

要在dask group中实现nunique,你必须使用聚合函数。

import pandas as pd
import dask.dataframe as dd

def chunk(s):
    '''
    The function applied to the
    individual partition (map)
    '''    
    return s.apply(lambda x: list(set(x)))


def agg(s):
    '''
    The function whic will aggrgate 
    the result from all the partitions(reduce)
    '''
    s = s._selected_obj    
    return s.groupby(level=list(range(s.index.nlevels))).sum()


def finalize(s):
    '''
    The optional functional that will be 
    applied to the result of the agg_tu functions
    '''
    return s.apply(lambda x: len(set(x)))


tunique = dd.Aggregation('tunique', chunk, agg,finalize)

df = pd.DataFrame({
'col': [0, 0, 1, 1, 2, 3, 3] * 10,
'g0': ['a', 'a', 'b', 'a', 'b', 'b', 'a'] * 10,
 })

 ddf = dd.from_pandas(df, npartitions=10)

 res = ddf.groupby(['col']).agg({'g0': tunique}).compute()
 print(res)
相关问题