From d2f9f0b367633cdd0c982fd08348ec691c93ec4a Mon Sep 17 00:00:00 2001 From: Luke Manley Date: Sat, 15 Feb 2025 03:21:20 -0500 Subject: [PATCH] fix: Adding a struct field using a literal raises InvalidOperationError (#21254) --- crates/polars-plan/src/dsl/function_expr/struct_.rs | 3 +-- py-polars/tests/unit/datatypes/test_struct.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/polars-plan/src/dsl/function_expr/struct_.rs b/crates/polars-plan/src/dsl/function_expr/struct_.rs index 1330ec1451a9..3a96b86cdc5b 100644 --- a/crates/polars-plan/src/dsl/function_expr/struct_.rs +++ b/crates/polars-plan/src/dsl/function_expr/struct_.rs @@ -245,8 +245,7 @@ pub(super) fn with_fields(args: &[Column]) -> PolarsResult { } let new_fields = fields.into_values().cloned().collect::>(); - let mut out = - StructChunked::from_series(ca.name().clone(), new_fields[0].len(), new_fields.iter())?; + let mut out = StructChunked::from_series(ca.name().clone(), ca.len(), new_fields.iter())?; out.zip_outer_validity(ca); Ok(out.into_column()) } diff --git a/py-polars/tests/unit/datatypes/test_struct.py b/py-polars/tests/unit/datatypes/test_struct.py index 93080c3fea35..d0865114c899 100644 --- a/py-polars/tests/unit/datatypes/test_struct.py +++ b/py-polars/tests/unit/datatypes/test_struct.py @@ -1227,6 +1227,18 @@ def test_nested_object_raises_15237() -> None: df.select(pl.struct("a")) +def test_empty_struct_with_fields_21095() -> None: + df = pl.DataFrame({"a": [{}, {}]}) + assert_frame_equal( + df.select(pl.col("a").struct.with_fields(a=pl.lit(42, pl.Int64))), + pl.DataFrame({"a": [{"a": 42}, {"a": 42}]}), + ) + assert_frame_equal( + df.select(pl.col("a").struct.with_fields(a=None)), + pl.DataFrame({"a": [{"a": None}, {"a": None}]}), + ) + + def test_cast_to_struct_needs_field_14083() -> None: with pytest.raises( InvalidOperationError, match="must specify one field in the struct"