Repository navigation
Open
Labels
dataframeioneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.parquet
Description
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
Metadata
Metadata
Assignees
Labels
dataframeioneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.parquet
Activity
jsignell commentedon Sep 3, 2020
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:
jorisvandenbossche commentedon Sep 3, 2020
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.
jorisvandenbossche commentedon Sep 3, 2020
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.jsignell commentedon Sep 3, 2020
Ok phew. I was starting to get paranoid :)
odovad commentedon Sep 3, 2020
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.
jorisvandenbossche commentedon Sep 3, 2020
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:
which results in different pyarrow Table schemas (from putting a
printstatement in dask'swrite_partitionafter converting the pandas dataframe to an arrow table and before writing it to parquet):So indeed, that gives a mismatch in the dtypes of the categories ("values" in the pyarrow repr above)
odovad commentedon Sep 3, 2020
Thanks @jorisvandenbossche and Pyarrow was more permissive before now, right?
jorisvandenbossche commentedon Sep 3, 2020
Indeed, and more speciifically, pyarrow started to require that when creating a single
_metadatafile that gathers the metadata of all partitions, the schemas are all equal (because that is the implicit assumption of such a_metadatafile)jorisvandenbossche commentedon Sep 3, 2020
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
categoriesare 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).odovad commentedon Sep 3, 2020
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.
jorisvandenbossche commentedon Sep 3, 2020
According to the docstring of the
schemakeyword, if you pass apyarrow.Schemaobject, 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:dask/dask/dataframe/io/parquet/core.py
Lines 349 to 358 in 0ca1607
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)odovad commentedon Sep 3, 2020
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 ?
jorisvandenbossche commentedon Sep 3, 2020
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)
odovad commentedon Sep 3, 2020
It works also for me, I was using dask 2.21. Thanks @jorisvandenbossche !
jsignell commentedon Sep 14, 2020
@rjzamora in case you have thoughts on whether we can do something better from the dask side.
rjzamora commentedon Sep 14, 2020
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:
This clearly states that the user should try modifying the
schema, but"infer"will definitely not work correctly for mismatchedCategoricaldtypes. Perhaps we need to improve the recommendation to refer to theschemaargument more generally?jsignell commentedon Sep 16, 2020
Is there a scenario where
schema="infer"is really the solution for resolving this error?rjzamora commentedon Sep 16, 2020
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 theconcatoperation results in a consistent type accross partitions?jsignell commentedon Sep 21, 2020
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.
chrisroat commentedon Dec 20, 2020
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:
dd.from_delayed(I re-use the function from the previous point)bryanwweber commentedon Mar 25, 2022
@rjzamora I can't reproduce the issue in the OP.
Regarding the quote above, should this issue be closed, or is there more to do in the
concatoperation?msebbah commentedon Apr 8, 2022
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'])bryanwweber commentedon Apr 8, 2022
@msebbah Can you please provide a complete minimal example to reproduce this issue? What version of Dask are you using?
dbalabka commentedon Mar 12, 2025
@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 hasdictionary<values=large_string, indices=int16, ordered=0>. I assume it should happen quite often with high-cardinality categorical columns that do not fit intoint8.I believe it can be a workaround by setting
int16explicitly likedf.to_parquet('does_not_work', schema={"name": pa.dictionary("int16", "string")}).Here is a minimal reproducible example: