繁体   English   中英

Dask:Dataframe groupBy 上的独特方法

[英]Dask: nunique method on Dataframe groupBy

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

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

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

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

见:

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

从源代码看来,您可以在 agg 之外做 nunique。

要在 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM