Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 28 additions & 8 deletions dask/dataframe/io/parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
import pandas as pd

from ..core import DataFrame, Series
from ..utils import UNKNOWN_CATEGORIES
from ..utils import (clear_known_categories, strip_unknown_categories,
UNKNOWN_CATEGORIES)
from ...base import tokenize
from ...compatibility import PY3, string_types
from ...delayed import delayed
Expand Down Expand Up @@ -518,8 +519,12 @@ def _read_pyarrow(fs, fs_token, paths, columns=None, filters=None,
if filters is not None:
raise NotImplementedError("Predicate pushdown not implemented")

if categories is not None:
raise NotImplementedError("Categorical reads not yet implemented")
if isinstance(categories, string_types):
categories = [categories]
elif categories is None:
categories = []
else:
categories = list(categories)

if isinstance(columns, tuple):
columns = list(columns)
Expand Down Expand Up @@ -553,10 +558,11 @@ def _read_pyarrow(fs, fs_token, paths, columns=None, filters=None,

all_columns = index_names + column_names

dtypes = _get_pyarrow_dtypes(schema)
dtypes = _get_pyarrow_dtypes(schema, categories)
dtypes = {storage_name_mapping.get(k, k): v for k, v in dtypes.items()}

meta = _meta_from_dtypes(all_columns, dtypes, index_names, column_index_names)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we don't know the actual categories at graph build time, we need to make sure any categorical columns/indices are marked as unknown categories (see http://dask.pydata.org/en/latest/dataframe-design.html#categoricals). The fastparquet reader handles this here: https://github.com/dask/dask/pull/3177/files#diff-410a8a0995091d42fbbbc5a50efda3aeL295, but this looks incorrect for the no-data case, as meta is returned directly on compute and would then have the string '__UNKNOWN_CATEGORIES__' in its categories.

Ideally we'd have two objects:

  • An empty frame/series that can be returned directly to the user on compute in the case of no data
  • An empty frame/series to be used as metadata that properly sets unknown categories

These should ideally be handled using the same code path (perhaps move logic to _meta_from_dtypes). You might also find dask.dataframe.utils.clear_known_categories (sets all categories to be unknown) and dask.dataframe.utils.strip_unknown_categories (removes unknown categories flags) to be useful.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adjusted it hopefully in the correct way. Moving the code to _meta_from_dtype depends on the pyarrow path also supporting known categoricals. I'm not sure how soon I'll get to that.

meta = clear_known_categories(meta, cols=categories)

if out_type == Series:
assert len(meta.columns) == 1
Expand All @@ -573,34 +579,48 @@ def _read_pyarrow(fs, fs_token, paths, columns=None, filters=None,
column_names,
index_names,
out_type == Series,
dataset.partitions)
dataset.partitions,
categories)
for i, piece in enumerate(dataset.pieces)
}
else:
meta = strip_unknown_categories(meta)
divisions = (None, None)
task_plan = {(task_name, 0): meta}

return out_type(task_plan, task_name, meta, divisions)


def _get_pyarrow_dtypes(schema):
def _get_pyarrow_dtypes(schema, categories):
dtypes = {}
for i in range(len(schema)):
field = schema[i]
numpy_dtype = field.type.to_pandas_dtype()
dtypes[field.name] = numpy_dtype

if categories:
for cat in categories:
dtypes[cat] = "category"

return dtypes


def _read_pyarrow_parquet_piece(fs, piece, columns, index_cols, is_series,
partitions):
partitions, categories):
import pyarrow as pa

with fs.open(piece.path, mode='rb') as f:
table = piece.read(columns=index_cols + columns,
partitions=partitions,
use_pandas_metadata=True,
file=f)
df = table.to_pandas()

if pa.__version__ < distutils.version.LooseVersion('0.9.0'):
df = table.to_pandas()
for cat in categories:
df[cat] = df[cat].astype('category')
else:
df = table.to_pandas(categories=categories)
has_index = not isinstance(df.index, pd.RangeIndex)

if not has_index and index_cols:
Expand Down
30 changes: 13 additions & 17 deletions dask/dataframe/io/tests/test_parquet.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,29 +306,30 @@ def test_roundtrip_from_pandas(tmpdir, write_engine, read_engine):
assert_eq(df, ddf)


def test_categorical(tmpdir):
check_fastparquet()
@write_read_engines_xfail
def test_categorical(tmpdir, write_engine, read_engine):
tmp = str(tmpdir)
df = pd.DataFrame({'x': ['a', 'b', 'c'] * 100}, dtype='category')
ddf = dd.from_pandas(df, npartitions=3)
dd.to_parquet(ddf, tmp)
dd.to_parquet(ddf, tmp, engine=write_engine)

ddf2 = dd.read_parquet(tmp, categories='x')
ddf2 = dd.read_parquet(tmp, categories='x', engine=read_engine)
assert ddf2.compute().x.cat.categories.tolist() == ['a', 'b', 'c']

ddf2 = dd.read_parquet(tmp, categories=['x'])
ddf2 = dd.read_parquet(tmp, categories=['x'], engine=read_engine)
assert ddf2.compute().x.cat.categories.tolist() == ['a', 'b', 'c']

# autocat
ddf2 = dd.read_parquet(tmp)
assert ddf2.compute().x.cat.categories.tolist() == ['a', 'b', 'c']
if read_engine != 'pyarrow':
ddf2 = dd.read_parquet(tmp, engine=read_engine)
assert ddf2.compute().x.cat.categories.tolist() == ['a', 'b', 'c']

ddf2.loc[:1000].compute()
df.index.name = 'index' # defaults to 'index' in this case
assert assert_eq(df, ddf2)
ddf2.loc[:1000].compute()
df.index.name = 'index' # defaults to 'index' in this case
assert assert_eq(df, ddf2)

# dereference cats
ddf2 = dd.read_parquet(tmp, categories=[])
ddf2 = dd.read_parquet(tmp, categories=[], engine=read_engine)

ddf2.loc[:1000].compute()
assert (df.x == ddf2.x).all()
Expand Down Expand Up @@ -888,14 +889,9 @@ def test_pyarrow_raises_filters_categoricals(tmpdir):

df.to_parquet(tmp, write_index=False, engine="pyarrow")

with pytest.raises(NotImplementedError) as m:
with pytest.raises(NotImplementedError):
dd.read_parquet(tmp, engine="pyarrow", filters=["A>1"])

with pytest.raises(NotImplementedError) as m:
dd.read_parquet(tmp, engine="pyarrow", categories=['A'])

assert m.match("Categorical reads not yet ")


def test_read_no_metadata(tmpdir, engine):
# use pyarrow.parquet to create a parquet file without
Expand Down
2 changes: 1 addition & 1 deletion docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ DataFrame
+++++++++

- Fixed bug in shuffle due to aggressive truncation (:pr:`3201`) `Matthew Rocklin`_
- Support specifying categorical columns on ``read_parquet`` with ``categories=[…]`` for ``engine="pyarrow"`` (:pr:`3177`) `Uwe Korn`_


Bag
Expand All @@ -38,7 +39,6 @@ DataFrame

- Bugfix to allow column assignment of pandas datetimes(:pr:`3164`) `Max Epstein`_


Bag
+++

Expand Down