diff --git a/python/cudf/cudf/core/column/column.py b/python/cudf/cudf/core/column/column.py index ac352a94a765..cd2f23f3170f 100644 --- a/python/cudf/cudf/core/column/column.py +++ b/python/cudf/cudf/core/column/column.py @@ -2290,12 +2290,12 @@ def cast(self, dtype: DtypeObj) -> ColumnBase: def astype(self, dtype: DtypeObj, copy: bool | None = False) -> ColumnBase: if self.dtype == dtype: result = self + elif isinstance(dtype, CategoricalDtype): + result = self.as_categorical_column(dtype) elif len(self) == 0: result = column_empty(0, dtype=dtype) else: - if isinstance(dtype, CategoricalDtype): - result = self.as_categorical_column(dtype) - elif is_dtype_obj_interval(dtype): + if is_dtype_obj_interval(dtype): result = self.as_interval_column(dtype) # type: ignore[arg-type] elif is_dtype_obj_list(dtype) or is_dtype_obj_struct(dtype): if isinstance(dtype, pd.ArrowDtype): diff --git a/python/cudf/cudf/tests/series/methods/test_astype.py b/python/cudf/cudf/tests/series/methods/test_astype.py index 10589af5c20b..175656d7786b 100644 --- a/python/cudf/cudf/tests/series/methods/test_astype.py +++ b/python/cudf/cudf/tests/series/methods/test_astype.py @@ -145,7 +145,12 @@ def test_cast_float_nan_to_bool_pandas_compat(): def test_empty_astype_always_castable(type1, type2, as_dtype, copy): ser = cudf.Series([], dtype=as_dtype(type1)) result = ser.astype(as_dtype(type2), copy=copy) - expected = cudf.Series([], dtype=as_dtype(type2)) + if type2 == "category": + # Empty astype to category inherits the source dtype as the + # categories dtype, matching pandas behavior. + expected = cudf.Series([], dtype=result.dtype) + else: + expected = cudf.Series([], dtype=as_dtype(type2)) assert_eq(result, expected) if not copy and cudf.dtype(type1) == cudf.dtype(type2): assert ser._column is result._column