8

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

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

4

3 回答 3

2

要在 dask groupby 中实现 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)
于 2017-12-21T18:49:03.133 回答
2

要扩展此评论,您可以nunique直接在 SeriesGroupBy 上使用:

import pandas as pd
import dask.dataframe as dd

d = {'col1': [1, 2, 3, 4], 'col2': [5, 6, 7, 8]}
df = pd.DataFrame(data=d)
ddf = dd.from_pandas(df, npartitions=2)
ddf.groupby(['col1']).col2.nunique().to_frame().compute()

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

于 2020-06-03T14:22:05.493 回答
1

看:

在 Dask 中使用 GroupBy 的自定义聚合函数构造模式和对应的计数函数

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

于 2017-09-07T19:55:04.100 回答