【问题标题】:Dask: nunique method on Dataframe groupByDask:Dataframe groupBy 上的独特方法
【发布时间】:2020-06-03 22:22:05
【问题描述】:

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

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

【问题讨论】:

  • [截至 2019 年第二季度] 适用于 Series 和 SeriesGroupBy。

标签: python dask dask-distributed


【解决方案1】:

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

【讨论】:

  • @mdurant 嘿,你能确认这是正确的方法还是有更有效的方法,谢谢
【解决方案2】:

要扩展 this comment,您可以直接在 SeriesGroupBy 上使用 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。

【讨论】:

    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2018-05-06
      • 2018-07-19
      • 2018-12-24
      • 2023-01-26
      • 2011-05-06
      • 2021-09-23
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      相关资源
      最近更新 更多