diff --git a/crates/polars-core/src/chunked_array/logical/categorical/ops/unique.rs b/crates/polars-core/src/chunked_array/logical/categorical/ops/unique.rs index 076099a9c33..7792fae8a54 100644 --- a/crates/polars-core/src/chunked_array/logical/categorical/ops/unique.rs +++ b/crates/polars-core/src/chunked_array/logical/categorical/ops/unique.rs @@ -7,6 +7,18 @@ use super::*; impl CategoricalChunked { pub fn unique(&self) -> PolarsResult { let cat_map = self.get_rev_map(); + if self.is_empty() { + // SAFETY: rev map is valid. + unsafe { + return Ok(CategoricalChunked::from_cats_and_rev_map_unchecked( + UInt32Chunked::full_null(self.name().clone(), 0), + cat_map.clone(), + self.is_enum(), + self.get_ordering(), + )); + } + }; + if self._can_fast_unique() { let ca = match &**cat_map { RevMapping::Local(a, _) => UInt32Chunked::from_iter_values( diff --git a/py-polars/tests/unit/operations/unique/test_unique.py b/py-polars/tests/unit/operations/unique/test_unique.py index 595ae1db59e..ff4a0cd10f3 100644 --- a/py-polars/tests/unit/operations/unique/test_unique.py +++ b/py-polars/tests/unit/operations/unique/test_unique.py @@ -154,6 +154,16 @@ def test_unique_categorical(input: list[str | None], output: list[str | None]) - assert_series_equal(result, expected) +def test_unique_categorical_global() -> None: + with pl.StringCache(): + pl.Series(["aaaa", "bbbb", "cccc"]) # pre-fill global cache + s = pl.Series(["a", "b", "c"], dtype=pl.Categorical) + s_empty = s.slice(0, 0) + + assert s_empty.unique().to_list() == [] + assert_series_equal(s_empty.cat.get_categories(), pl.Series(["a", "b", "c"])) + + def test_unique_with_null() -> None: df = pl.DataFrame( {