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: Preserve lexical ordering on concat #15753

Merged
merged 1 commit into from
Apr 19, 2024
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
@@ -1,15 +1,20 @@
use super::*;

impl CategoricalChunked {
pub fn full_null(name: &str, is_enum: bool, length: usize) -> CategoricalChunked {
pub fn full_null(
name: &str,
is_enum: bool,
length: usize,
ordering: CategoricalOrdering,
) -> CategoricalChunked {
let cats = UInt32Chunked::full_null(name, length);

unsafe {
CategoricalChunked::from_cats_and_rev_map_unchecked(
cats,
Arc::new(RevMapping::default()),
is_enum,
Default::default(),
ordering,
)
}
}
Expand Down
10 changes: 7 additions & 3 deletions crates/polars-core/src/series/ops/null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ impl Series {
ArrayChunked::full_null_with_dtype(name, size, inner_dtype, *width).into_series()
},
#[cfg(feature = "dtype-categorical")]
dt @ (DataType::Categorical(rev_map, _) | DataType::Enum(rev_map, _)) => {
let mut ca =
CategoricalChunked::full_null(name, matches!(dt, DataType::Enum(_, _)), size);
dt @ (DataType::Categorical(rev_map, ord) | DataType::Enum(rev_map, ord)) => {
let mut ca = CategoricalChunked::full_null(
name,
matches!(dt, DataType::Enum(_, _)),
size,
*ord,
);
// ensure we keep the rev-map of a cleared series
if let Some(rev_map) = rev_map {
unsafe { ca.set_rev_map(rev_map.clone(), false) }
Expand Down
14 changes: 14 additions & 0 deletions py-polars/tests/unit/datatypes/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,3 +812,17 @@ def test_cast_from_cat_to_numeric() -> None:

s = pl.Series(["1", "2", "3"], dtype=pl.Categorical)
assert s.cast(pl.UInt8).sum() == 6


def test_cat_preserve_lexical_ordering_on_clear() -> None:
s = pl.Series("a", ["a", "b"], dtype=pl.Categorical(ordering="lexical"))
s2 = s.clear()
assert s.dtype == s2.dtype


def test_cat_preserve_lexical_ordering_on_concat() -> None:
dtype = pl.Categorical(ordering="lexical")

df = pl.DataFrame({"x": ["b", "a", "c"]}).with_columns(pl.col("x").cast(dtype))
df2 = pl.concat([df, df])
assert df2["x"].dtype == dtype
Loading