Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Add unique fast path for empty categoricals #20536

Merged
merged 1 commit into from
Jan 3, 2025
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
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
Loading