Skip to content

Commit

Permalink
fix: Add unique fast path for empty categoricals (#20536)
Browse files Browse the repository at this point in the history
  • Loading branch information
mcrumiller authored Jan 3, 2025
1 parent 11fa6de commit 5c9bb71
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ use super::*;
impl CategoricalChunked {
pub fn unique(&self) -> PolarsResult<Self> {
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(
Expand Down
10 changes: 10 additions & 0 deletions py-polars/tests/unit/operations/unique/test_unique.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down

0 comments on commit 5c9bb71

Please sign in to comment.