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: Cast empty lists and lists of only nulls without an inner dtype #15525

Closed
wants to merge 5 commits into from
Closed
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
6 changes: 6 additions & 0 deletions crates/polars-core/src/chunked_array/upstream_traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,12 @@ impl FromIterator<Option<Series>> for ListChunked {
builder.append_series(first_s).unwrap();

for opt_s in it {
if opt_s.is_some() {
debug_assert_eq!(
opt_s.clone().unwrap().dtype(),
first_s.dtype()
);
}
builder.append_opt_series(opt_s.as_ref()).unwrap();
}
builder.finish()
Expand Down
12 changes: 11 additions & 1 deletion crates/polars-core/src/series/any_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -493,9 +493,19 @@ fn any_values_to_list(
let mut valid = true;
#[allow(unused_mut)]
let mut out: ListChunked = if inner_type == &DataType::Null {
let mut first_value_dtype = DataType::Null;
let mut set_first = false;
avs.iter()
.map(|av| match av {
AnyValue::List(b) => Some(b.clone()),
AnyValue::List(b) => {
if !set_first && first_value_dtype != *b.dtype() {
first_value_dtype = b.dtype().clone();
set_first = true;
} else if b.is_empty() || b.null_count() == b.len() {
return b.cast(&first_value_dtype).ok();
}
Some(b.clone())
},
AnyValue::Null => None,
_ => {
valid = false;
Expand Down
15 changes: 15 additions & 0 deletions py-polars/tests/unit/datatypes/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -831,3 +831,18 @@ def test_take_list_15719() -> None:
)

assert_frame_equal(df, expected)


@pytest.mark.parametrize(
("values", "dtype", "full_dtype"),
[
([["a"], [], [None], None], pl.List, pl.List(pl.String)),
([[1], [], [None], None], pl.List, pl.List(pl.Int64)),
([[], None, ["a"]], pl.List, pl.List(pl.String)),
],
)
def test_list_anyvalue_empty_list(
values: list[Any], dtype: PolarsDataType, full_dtype: PolarsDataType
) -> None:
s = pl.Series("a", values, dtype=dtype)
assert_series_equal(s, pl.Series("a", values, dtype=full_dtype))
Loading