Skip to content

Commit

Permalink
Generalize clear_known_categories utility (dask#11059)
Browse files Browse the repository at this point in the history
  • Loading branch information
rjzamora authored Apr 23, 2024
1 parent 5822a61 commit 48c418c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
12 changes: 12 additions & 0 deletions dask/dataframe/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,18 @@ def test_concat_unions_categoricals():
tm.assert_frame_equal(_concat(frames5), pd.concat(frames6))


@pytest.mark.gpu
def test_unknown_categories_cudf():
# We should always start with unknown categories
# if `clear_known_categories` is working.
pytest.importorskip("dask_cudf")

with dask.config.set({"dataframe.backend": "cudf"}):
ddf = dd.from_dict({"a": [0, 1, 0]}, npartitions=1)
ddf["a"] = ddf["a"].astype("category")
assert not ddf["a"].cat.known


# TODO: Remove the filterwarnings below
@pytest.mark.parametrize(
"numeric_only",
Expand Down
13 changes: 7 additions & 6 deletions dask/dataframe/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
)
from dask.dataframe._compat import PANDAS_GE_150, tm # noqa: F401
from dask.dataframe.dispatch import ( # noqa : F401
is_categorical_dtype_dispatch,
make_meta,
make_meta_obj,
meta_nonempty,
Expand Down Expand Up @@ -283,22 +284,22 @@ def clear_known_categories(x, cols=None, index=True, dtype_backend=None):
# categorical accessor is not yet available
return x

if isinstance(x, (pd.Series, pd.DataFrame)):
if not is_index_like(x):
x = x.copy()
if isinstance(x, pd.DataFrame):
if is_dataframe_like(x):
mask = x.dtypes == "category"
if cols is None:
cols = mask[mask].index
elif not mask.loc[cols].all():
raise ValueError("Not all columns are categoricals")
for c in cols:
x[c] = x[c].cat.set_categories([UNKNOWN_CATEGORIES])
elif isinstance(x, pd.Series):
if isinstance(x.dtype, pd.CategoricalDtype):
elif is_series_like(x):
if is_categorical_dtype_dispatch(x.dtype):
x = x.cat.set_categories([UNKNOWN_CATEGORIES])
if index and isinstance(x.index, pd.CategoricalIndex):
if index and is_categorical_dtype_dispatch(x.index.dtype):
x.index = x.index.set_categories([UNKNOWN_CATEGORIES])
elif isinstance(x, pd.CategoricalIndex):
elif is_categorical_dtype_dispatch(x.dtype):
x = x.set_categories([UNKNOWN_CATEGORIES])
return x

Expand Down

0 comments on commit 48c418c

Please sign in to comment.