Skip to content

Commit

Permalink
fix(rust, python): keep name when sorting categorical in lexial order (
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed Jan 4, 2023
1 parent a52c3b5 commit 1067ec3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
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"]}

0 comments on commit 1067ec3

Please sign in to comment.