AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-4841654

Dave's questions

Martin Hope
Dave
Asked: 2025-04-05 00:11:43 +0800 CST

Problemas ao refatorar pandas.DataFrame.groupby.aggregate para dask.dataframe.groupby.aggregate com agregação personalizada

  • 6

Gostaria de executar groupby e aggregation sobre um dataframe onde a agregação une strings com o mesmo id. O df se parece com isso:

In [1]: df = pd.DataFrame.from_dict({'id':[1,1,2,2,2,3], 'name':['a','b','c','d','e','f']})
In [2]: df
Out[2]:
   id name
0   1    a
1   1    b
2   2    c
3   2    d
4   2    e
5   3    f

Eu tenho isso funcionando no Pandas assim:

def list_aggregator(x):
    return '|'.join(x)

df2 = pd.DataFrame.from_dict('id':[], 'name':[])
df2['id'] = df['id'].drop_duplicates()
df2['name'] = df['name'].groupby(df['id']).agg(list_aggregator).values

Produz:

In [26]: df2
Out[26]:
   id   name
0   1    a|b
2   2  c|d|e
5   3      f

Para Dask, meu entendimento (dos documentos ) é que você tem que dizer a Dask o que fazer para agregar dentro de chunks, e então o que fazer com esses chunks agregados. Em ambos os casos, eu quero fazer o equivalente a '|'.join(). Então:

ddf = dd.from_pandas(df, 2)
ddf2 = dd.from_pandas(pd.DataFrame.from_dict({'id':[],'name':[]}))
ddf2['id'] = ddf['id'].drop_duplicates()

dd_list_aggregation = dd.Aggregation(
    'list_aggregation',
    list_aggregator,  # chunks are aggregated into strings with 1 string per chunk
    list_aggregator,  # per-chunk strings are aggregated into a single string per id
)

ddf2['name'] = ddf['name'].groupby(ddf['id']).agg(dd_list_aggregation).values

O resultado esperado é o acima (ou, na verdade, nada, já que ainda não chamei ddf2.compute()), mas recebo este erro:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_core.py:446, in Expr.__getattr__(self, key)
    445 try:
--> 446     return object.__getattribute__(self, key)
    447 except AttributeError as err:

File ~/miniconda3/envs/test/lib/python3.10/functools.py:981, in cached_property.__get__(self, instance, owner)
    980 if val is _NOT_FOUND:
--> 981     val = self.func(instance)
    982     try:

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_groupby.py:206, in GroupByApplyConcatApply._meta_chunk(self)
    205 meta = meta_nonempty(self.frame._meta)
--> 206 return self.chunk(meta, *self._by_meta, **self.chunk_kwargs)

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask/dataframe/groupby.py:1200, in _groupby_apply_funcs(df, *by, **kwargs)
   1199 for result_column, func, func_kwargs in funcs:
-> 1200     r = func(grouped, **func_kwargs)
   1202     if isinstance(r, tuple):

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask/dataframe/groupby.py:1276, in _apply_func_to_column(df_like, column, func)
   1275 if column is None:
-> 1276     return func(df_like)
   1278 return func(df_like[column])

Cell In[88], line 2
      1 def dd_list_aggregator(x):
----> 2     return '|'.join(x[1])

File ~/miniconda3/envs/test/lib/python3.10/site-packages/pandas/core/base.py:245, in SelectionMixin.__getitem__(self, key)
    244     raise KeyError(f"Column not found: {key}")
--> 245 ndim = self.obj[key].ndim
    246 return self._gotitem(key, ndim=ndim)

AttributeError: 'str' object has no attribute 'ndim'

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
Cell In[96], line 1
----> 1 ddf2['name'] = ddf['name'].groupby(ddf['id']).agg(dd_list_aggregation).values

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_groupby.py:1907, in GroupBy.agg(self, *args, **kwargs)
   1906 def agg(self, *args, **kwargs):
-> 1907     return self.aggregate(*args, **kwargs)

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_groupby.py:1891, in GroupBy.aggregate(self, arg, split_every, split_out, shuffle_method, **kwargs)
   1888 if arg == "size":
   1889     return self.size()
-> 1891 return new_collection(
   1892     GroupbyAggregation(
   1893         self.obj.expr,
   1894         arg,
   1895         self.observed,
   1896         self.dropna,
   1897         split_every,
   1898         split_out,
   1899         self.sort,
   1900         shuffle_method,
   1901         self._slice,
   1902         *self.by,
   1903     )
   1904 )

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_collection.py:4440, in new_collection(expr)
   4438 def new_collection(expr):
   4439     """Create new collection from an expr"""
-> 4440     meta = expr._meta
   4441     expr._name  # Ensure backend is imported
   4442     return get_collection_type(meta)(expr)

File ~/miniconda3/envs/test/lib/python3.10/functools.py:981, in cached_property.__get__(self, instance, owner)
    979 val = cache.get(self.attrname, _NOT_FOUND)
    980 if val is _NOT_FOUND:
--> 981     val = self.func(instance)
    982     try:
    983         cache[self.attrname] = val

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_groupby.py:432, in GroupbyAggregation._meta(self)
    430 @functools.cached_property
    431 def _meta(self):
--> 432     return self._lower()._meta

File ~/miniconda3/envs/test/lib/python3.10/functools.py:981, in cached_property.__get__(self, instance, owner)
    979 val = cache.get(self.attrname, _NOT_FOUND)
    980 if val is _NOT_FOUND:
--> 981     val = self.func(instance)
    982     try:
    983         cache[self.attrname] = val

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_reductions.py:425, in ApplyConcatApply._meta(self)
    423 @functools.cached_property
    424 def _meta(self):
--> 425     meta = self._meta_chunk
    426     aggregate = self.aggregate or (lambda x: x)
    427     if self.combine:

File ~/miniconda3/envs/test/lib/python3.10/site-packages/dask_expr/_core.py:451, in Expr.__getattr__(self, key)
    447 except AttributeError as err:
    448     if key.startswith("_meta"):
    449         # Avoid a recursive loop if/when `self._meta*`
    450         # produces an `AttributeError`
--> 451         raise RuntimeError(
    452             f"Failed to generate metadata for {self}. "
    453             "This operation may not be supported by the current backend."
    454         )
    456     # Allow operands to be accessed as attributes
    457     # as long as the keys are not already reserved
    458     # by existing methods/properties
    459     _parameters = type(self)._parameters

RuntimeError: Failed to generate metadata for DecomposableGroupbyAggregation(frame=df['name'], arg=<dask.dataframe.groupby.Aggregation object at 0x7f052960b850>, observed=False, split_out=1). This operation may not be supported by the current backend.

Meu pensamento é que objetos numéricos são esperados, mas o backend é o pandas, então manipulações de strings devem ser possíveis, certo?

pandas
  • 1 respostas
  • 41 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve