Skip to content

Commit

Permalink
fix(rust): Qcut all nulls panics (#18667)
Browse files Browse the repository at this point in the history
Co-authored-by: ritchie <ritchie46@gmail.com>
  • Loading branch information
yarimiz and ritchie46 authored Sep 11, 2024
1 parent db1b15f commit eac567f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
14 changes: 9 additions & 5 deletions crates/polars-ops/src/series/ops/cut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,19 @@ pub fn qcut(
) -> PolarsResult<Series> {
polars_ensure!(!probs.iter().any(|x| x.is_nan()), ComputeError: "quantiles cannot be NaN");

if s.null_count() == s.len() {
// If we only have nulls we don't have any breakpoints.
return Ok(Series::full_null(
s.name().clone(),
s.len(),
&DataType::Categorical(None, Default::default()),
));
}

let s = s.cast(&DataType::Float64)?;
let s2 = s.sort(SortOptions::default())?;
let ca = s2.f64()?;

if ca.null_count() == ca.len() {
// If we only have nulls we don't have any breakpoints.
return cut(&s, vec![], labels, left_closed, include_breaks);
}

let f = |&p| {
ca.quantile(p, QuantileInterpolOptions::Linear)
.unwrap()
Expand Down
9 changes: 9 additions & 0 deletions py-polars/tests/unit/operations/test_qcut.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ def test_qcut_full_null() -> None:
assert_series_equal(result, expected, categorical_as_str=True)


def test_qcut_full_null_with_labels() -> None:
s = pl.Series("a", [None, None, None, None])

result = s.qcut([0.25, 0.50], labels=["1", "2", "3"])

expected = pl.Series("a", [None, None, None, None], dtype=pl.Categorical)
assert_series_equal(result, expected, categorical_as_str=True)


def test_qcut_allow_duplicates() -> None:
s = pl.Series([1, 2, 2, 3])

Expand Down

0 comments on commit eac567f

Please sign in to comment.