Skip to content

Unable to write parquet with "empty" categorical column with pyarrow engine #6587

Open

Description

@odovad

I encountered an issue when working on a concat involving multiples files.
It seems that the issue happens also when applied on only one file with a partition containing a categorical column with no values.

Maybe this issue is linked : Issue 6243
If I am not mistaken, it worked with Pyarrow 0.17.1

import dask.dataframe as dd
import pandas as pd

names = [ 'name']
address = names

df1 = dd.from_pandas(pd.DataFrame({'name':names}), npartitions=1)
df2 = dd.from_pandas(pd.DataFrame({'address':address}), npartitions=1)
df1['name'] = df1['name'].astype('category')

df = dd.concat([df1, df2])
del df['address']

df.to_parquet('does_not_work')

The error that is raised :

RuntimeError                              Traceback (most recent call last)
/opt/conda/lib/python3.8/site-packages/dask/dataframe/io/parquet/arrow.py in _append_row_groups(metadata, md)
     33     try:
---> 34         metadata.append_row_groups(md)
     35     except RuntimeError as err:

/opt/conda/lib/python3.8/site-packages/pyarrow/_parquet.pyx in pyarrow._parquet.FileMetaData.append_row_groups()

RuntimeError: AppendRowGroups requires equal schemas.

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-46-4faae0e6b3fa> in <module>
     12 del df['address']
     13 
---> 14 df.to_parquet('does_not_work')

/opt/conda/lib/python3.8/site-packages/dask/dataframe/core.py in to_parquet(self, path, *args, **kwargs)
   3948         from .io import to_parquet
   3949 
-> 3950         return to_parquet(self, path, *args, **kwargs)
   3951 
   3952     @derived_from(pd.DataFrame)

/opt/conda/lib/python3.8/site-packages/dask/dataframe/io/parquet/core.py in to_parquet(df, path, engine, compression, write_index, append, ignore_divisions, partition_on, storage_options, write_metadata_file, compute, compute_kwargs, schema, **kwargs)
    506         if compute_kwargs is None:
    507             compute_kwargs = dict()
--> 508         out = out.compute(**compute_kwargs)
    509     return out
    510 

/opt/conda/lib/python3.8/site-packages/dask/base.py in compute(self, **kwargs)
    165         dask.base.compute
    166         """
--> 167         (result,) = compute(self, traverse=False, **kwargs)
    168         return result
    169 

/opt/conda/lib/python3.8/site-packages/dask/base.py in compute(*args, **kwargs)
    445         postcomputes.append(x.__dask_postcompute__())
    446 
--> 447     results = schedule(dsk, keys, **kwargs)
    448     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    449 

/opt/conda/lib/python3.8/site-packages/dask/threaded.py in get(dsk, result, cache, num_workers, pool, **kwargs)
     74                 pools[thread][num_workers] = pool
     75 
---> 76     results = get_async(
     77         pool.apply_async,
     78         len(pool._pool),

/opt/conda/lib/python3.8/site-packages/dask/local.py in get_async(apply_async, num_workers, dsk, result, cache, get_id, rerun_exceptions_locally, pack_exception, raise_exception, callbacks, dumps, loads, **kwargs)
    484                         _execute_task(task, data)  # Re-execute locally
    485                     else:
--> 486                         raise_exception(exc, tb)
    487                 res, worker_id = loads(res_info)
    488                 state["cache"][key] = res

/opt/conda/lib/python3.8/site-packages/dask/local.py in reraise(exc, tb)
    314     if exc.__traceback__ is not tb:
    315         raise exc.with_traceback(tb)
--> 316     raise exc
    317 
    318 

/opt/conda/lib/python3.8/site-packages/dask/local.py in execute_task(key, task_info, dumps, loads, get_id, pack_exception)
    220     try:
    221         task, data = loads(task_info)
--> 222         result = _execute_task(task, data)
    223         id = get_id()
    224         result = dumps((result, id))

/opt/conda/lib/python3.8/site-packages/dask/core.py in _execute_task(arg, cache, dsk)
    119         # temporaries by their reference count and can execute certain
    120         # operations in-place.
--> 121         return func(*(_execute_task(a, cache) for a in args))
    122     elif not ishashable(arg):
    123         return arg

/opt/conda/lib/python3.8/site-packages/dask/utils.py in apply(func, args, kwargs)
     27 def apply(func, args, kwargs=None):
     28     if kwargs:
---> 29         return func(*args, **kwargs)
     30     else:
     31         return func(*args)

/opt/conda/lib/python3.8/site-packages/dask/dataframe/io/parquet/arrow.py in write_metadata(parts, fmd, fs, path, append, **kwargs)
   1034                 i_start = 1
   1035             for i in range(i_start, len(parts)):
-> 1036                 _append_row_groups(_meta, parts[i][0]["meta"])
   1037             with fs.open(metadata_path, "wb") as fil:
   1038                 _meta.write_metadata_file(fil)

/opt/conda/lib/python3.8/site-packages/dask/dataframe/io/parquet/arrow.py in _append_row_groups(metadata, md)
     35     except RuntimeError as err:
     36         if "requires equal schemas" in str(err):
---> 37             raise RuntimeError(
     38                 "Schemas are inconsistent, try using "
     39                 '`to_parquet(..., schema="infer")`, or pass an explicit '

RuntimeError: Schemas are inconsistent, try using `to_parquet(..., schema="infer")`, or pass an explicit pyarrow schema.

Environment:

  • Dask version: 2.24.0
  • Pyarrow version: 1.0.1
  • Python version: 3.8
  • Operating System: Dask-Dev image
  • Install method (conda, pip, source) : Dask-Dev image

Activity

  1. jsignell commented on Sep 3, 2020

    @jsignell
    Member

    Thanks for reporting this @odovad. I am not sure if this is a pyarrow bug or not (ping @jorisvandenbossche just in case).

    As a workaround you can specify the schema explicitly. For instance the following seems to work as expected:

    import dask.dataframe as dd
    import pandas as pd
    import pyarrow as pa
    
    names = [ 'name']
    address = names
    
    df1 = dd.from_pandas(pd.DataFrame({'name':names}), npartitions=1)
    df2 = dd.from_pandas(pd.DataFrame({'address':address}), npartitions=1)
    df1['name'] = df1['name'].astype('category')
    
    df = dd.concat([df1, df2])
    del df['address']
    
    df.to_parquet('does_not_work', engine="pyarrow", schema={"name": pa.string()})
  2. jorisvandenbossche commented on Sep 3, 2020

    @jorisvandenbossche
    Member

    Hmm, with both pyarrow master and dask master, the example of the OP works for me.

    With released versions it indeed fails. So it might be a recent change in dask fixed it? In any case, in principle the issue with empty / all null partitions should only come up with object dtype columns, where pyarrow then cannot correctly infer the type. But in theory for categorical columns this shouldn't be a problem.

  3. jorisvandenbossche commented on Sep 3, 2020

    @jorisvandenbossche
    Member

    Hmm, with both pyarrow master and dask master, the example of the OP works for me.

    Whoops, sorry, in my dev environment I have also fastparquet installed, which was being used by default. With engine="pyarrow" it still fails with master versions of both.

  4. jsignell commented on Sep 3, 2020

    @jsignell
    Member

    With engine="pyarrow" it still fails with master versions of both.

    Ok phew. I was starting to get paranoid :)

  5. odovad commented on Sep 3, 2020

    @odovad
    Author

    Thanks @jsignell @jorisvandenbossche.
    I agree, it seems to work when specifying the schema, but we have to pass a pa.schema like pa.schema({'name':pa.dictionary('int16', 'string')}).
    I thought I could have issues with the dtype of the "index_type" of pa.dictionary since dask df._meta represents all "dictionary" fields with int8 by default and I thought the issue was due to a mismatch linked to dtypes of categories.

  6. jorisvandenbossche commented on Sep 3, 2020

    @jorisvandenbossche
    Member

    So looking a bit into it: the problem is that the two partitions (at least the actaul pandas dataframe stored in it) have a different categorical dtype:

    In [21]: df.partitions[0].compute().name.dtype
    Out[21]: CategoricalDtype(categories=['name'], ordered=False)
    
    In [22]: df.partitions[1].compute().name.dtype
    Out[22]: CategoricalDtype(categories=[], ordered=False)
    

    which results in different pyarrow Table schemas (from putting a print statement in dask's write_partition after converting the pandas dataframe to an arrow table and before writing it to parquet):

    pyarrow.Table
    name: dictionary<values=string, indices=int8, ordered=0>
    __null_dask_index__: int64
    pyarrow.Table
    name: dictionary<values=null, indices=int8, ordered=0>
    __null_dask_index__: int64
    

    So indeed, that gives a mismatch in the dtypes of the categories ("values" in the pyarrow repr above)

  7. odovad commented on Sep 3, 2020

    @odovad
    Author

    Thanks @jorisvandenbossche and Pyarrow was more permissive before now, right?

  8. jorisvandenbossche commented on Sep 3, 2020

    @jorisvandenbossche
    Member

    Indeed, and more speciifically, pyarrow started to require that when creating a single _metadata file that gathers the metadata of all partitions, the schemas are all equal (because that is the implicit assumption of such a _metadata file)

  9. jorisvandenbossche commented on Sep 3, 2020

    @jorisvandenbossche
    Member

    So in the and, this comes a bit down to what I mentioned originally: in theory this issue only happens with empty or all null object dtype columns. But here it's a categorical columns but where the categories are an empty object dtype Index .. (so if pandas would have a proper string dtype, and support for that in categorical dtype, dask could ensure that the categorical dtype, even if empty, has the correct dtype for the categories).

  10. odovad commented on Sep 3, 2020

    @odovad
    Author

    Ok, thanks. So for now, we have to specify the full schema? Because I've noticed that the columns passed to schema in to_parquet are the columns we'll get in our final parquet file.

  11. jorisvandenbossche commented on Sep 3, 2020

    @jorisvandenbossche
    Member

    According to the docstring of the schema keyword, if you pass a pyarrow.Schema object, it needs to be the full schema, but if you pass a dict, you should be able to only specify a single column, and the rest still gets inferred:

    schema : Schema object, dict, or {"infer", None}, optional
    Global schema to use for the output dataset. Alternatively, a `dict`
    of pyarrow types can be specified (e.g. `schema={"id": pa.string()}`).
    For this case, fields excluded from the dictionary will be inferred
    from `_meta_nonempty`. If "infer", the first non-empty and non-null
    partition will be used to infer the type for "object" columns. If
    None (default), we let the backend infer the schema for each distinct
    output partition. If the partitions produce inconsistent schemas,
    pyarrow will throw an error when writing the shared _metadata file.
    Note that this argument is ignored by the "fastparquet" engine.

    So if that's not happening, that would be a bug in the new keyword.

    Note that in your case, you might also be able to get away with schema="infer" (at least for the toy example)

  12. odovad commented on Sep 3, 2020

    @odovad
    Author

    Thanks, when passing a dict (like in @jsignell example), I get a 'dict' object has no attribute 'names' error.
    I'm the only one or dicts do work ?

  13. jorisvandenbossche commented on Sep 3, 2020

    @jorisvandenbossche
    Member

    For me the example of @jsignell works using dask 2.25 and pyarrow 1.0 (the example does only have one column though, so it doesn't really ensure the other columns were not dropped)

  14. odovad commented on Sep 3, 2020

    @odovad
    Author

    It works also for me, I was using dask 2.21. Thanks @jorisvandenbossche !

  15. jsignell commented on Sep 14, 2020

    @jsignell
    Member

    @rjzamora in case you have thoughts on whether we can do something better from the dask side.

  16. rjzamora commented on Sep 14, 2020

    @rjzamora
    Member

    Thanks for the ping - It looks like the new schema options address this issue reasonably well. I think the docstring is reasonably clear, but I guess the error message could be improved:

    RuntimeError: Schemas are inconsistent, try using `to_parquet(..., schema="infer")`, or pass an explicit pyarrow schema.
    

    This clearly states that the user should try modifying the schema, but "infer" will definitely not work correctly for mismatched Categorical dtypes. Perhaps we need to improve the recommendation to refer to the schema argument more generally?

  17. jsignell commented on Sep 16, 2020

    @jsignell
    Member

    Is there a scenario where schema="infer" is really the solution for resolving this error?

  18. rjzamora commented on Sep 16, 2020

    @rjzamora
    Member

    Is there a scenario where schema="infer" is really the solution for resolving this error?

    Good question - With schema="infer", the first partition will be used to infer a pyarrow schema, and then other partitions will be sampled if the first partition contains null "object"-type columns (we keep sampling untill we hve a non-null partition for each "object" column). Overall, we are targeting pandas "object" types, rather than Categorical.

    We may be able to improve "infer" to handle mismatched categorical columns, but it may make more sense to ensure the concat operation results in a consistent type accross partitions?

  19. jsignell commented on Sep 21, 2020

    @jsignell
    Member

    Ah ok. Thanks for explaining that. I think improving concat makes more sense in this case, but the error message is a nice low-hanging fruit. I'll open a PR for that in the meantime.

  20. chrisroat commented on Dec 20, 2020

    @chrisroat
    Contributor

    I don't want to hijack this thread, but I hit the empty dataframe w/ object dtype issue and the internet lead me here. The error message was helpful @jsignell, and I was able to workaround. I had a column with a variable length array, and I could make it work with a pa.list_(pa.float32()) type.

    Is there a place this is being tracked/discussed, as there are now 3 levels where to sync up the schema to be ready for empty partitions:

    • During initial calculation of dataframe, if data is empty. (In an ideal world, returning None is easier than a faked empty dataframe)
    • As the meta argument for dd.from_delayed (I re-use the function from the previous point)
    • During I/O to pyarrow (for just object columns, in a likely different section of code, using pyarrow data types)
  21. bryanwweber commented on Mar 25, 2022

    @bryanwweber
    Contributor

    @rjzamora I can't reproduce the issue in the OP.

    We may be able to improve "infer" to handle mismatched categorical columns, but it may make more sense to ensure the concat operation results in a consistent type accross partitions?

    Regarding the quote above, should this issue be closed, or is there more to do in the concat operation?

  22. msebbah commented on Apr 8, 2022

    @msebbah

    Same issue for me.
    I've been through with this workaround:
    for c in df.dtypes[df.dtypes == 'category'].index : df[c] = df[c].cat.add_categories(['default'])

  23. bryanwweber commented on Apr 8, 2022

    @bryanwweber
    Contributor

    @msebbah Can you please provide a complete minimal example to reproduce this issue? What version of Dask are you using?

  24. added
    needs attention
    on Jan 6, 2025
  25. dbalabka commented on Mar 12, 2025

    @dbalabka
    Contributor

    @bryanwweber, In my case, the problem with categorical values is that partitions contain different sets of values, leading to a schema mismatch during the Parque conversion.

    The problem is that one partition has dictionary<values=string, indices=int8, ordered=0> type but another has dictionary<values=large_string, indices=int16, ordered=0>. I assume it should happen quite often with high-cardinality categorical columns that do not fit into int8.

    I believe it can be a workaround by setting int16 explicitly like df.to_parquet('does_not_work', schema={"name": pa.dictionary("int16", "string")}).

    Here is a minimal reproducible example:

    import pandas as pd
    import numpy as np
    import pyarrow as pa
    import dask.dataframe as dd
    
    names = [ 'name']
    address = names
    
    df1 = (
      dd
      .from_pandas(pd.DataFrame({'name':np.tile([f'A{i}' for i in range(1, 250)], 10)}), npartitions=1)
    )
    
    df2 = (
      dd
      .from_pandas(pd.DataFrame({'name':np.tile([f'A{i}' for i in range(251, 501)], 10)}), npartitions=1)
    )
    
    df = dd.concat([df1, df2]).astype('category')
    
    df.to_parquet('does_not_work')
    ValueError: Failed to convert partition to expected pyarrow schema:
        `ArrowInvalid('Integer value 172 not in range: -128 to 127', 'Conversion failed for column name with type category')`
    
    Expected partition schema:
        name: dictionary<values=string, indices=int8, ordered=0>
        __null_dask_index__: int64
    
    Received partition schema:
        name: dictionary<values=large_string, indices=int16, ordered=0>
        __null_dask_index__: int64
    
    This error *may* be resolved by passing in schema information for
    the mismatched column(s) using the `schema` keyword in `to_parquet`.
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dataframeioneeds attentionparquet

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions