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(rust, python): keep name when sorting categorical in lexial order #6029

Merged
merged 1 commit into from
Jan 4, 2023
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
5 changes: 4 additions & 1 deletion polars/polars-core/src/chunked_array/ops/sort/categorical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,14 @@ impl CategoricalChunked {
);
let cats: NoNull<UInt32Chunked> =
vals.into_iter().map(|(idx, _v)| idx).collect_trusted();
let mut cats = cats.into_inner();
cats.rename(self.name());

// safety:
// we only reordered the indexes so we are still in bounds
unsafe {
CategoricalChunked::from_cats_and_rev_map_unchecked(
cats.into_inner(),
cats,
self.get_rev_map().clone(),
)
}
Expand Down
17 changes: 17 additions & 0 deletions py-polars/tests/unit/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,20 @@ def test_categorical_in_struct_nulls() -> None:
assert s[0] == {"job": None, "counts": 3}
assert s[1] == {"job": "doctor", "counts": 2}
assert s[2] == {"job": "waiter", "counts": 1}


def test_sort_categoricals_6014() -> None:
with pl.StringCache():
# create basic categorical
df1 = pl.DataFrame({"key": ["bbb", "aaa", "ccc"]}).with_column(
pl.col("key").cast(pl.Categorical)
)
# create lexically-ordered categorical
df2 = pl.DataFrame({"key": ["bbb", "aaa", "ccc"]}).with_column(
pl.col("key").cast(pl.Categorical).cat.set_ordering("lexical")
)

out = df1.sort("key")
assert out.to_dict(False) == {"key": ["bbb", "aaa", "ccc"]}
out = df2.sort("key")
assert out.to_dict(False) == {"key": ["aaa", "bbb", "ccc"]}