From 50f7f0eca2e0a74dff5c82cc15e0ee9a32818972 Mon Sep 17 00:00:00 2001 From: "Casagrande, Sandro" Date: Sun, 21 Jul 2024 23:02:09 +0200 Subject: [PATCH] fix named_expr with schema in struct and added corresponding test --- py-polars/polars/functions/as_datatype.py | 2 +- py-polars/tests/unit/datatypes/test_struct.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/py-polars/polars/functions/as_datatype.py b/py-polars/polars/functions/as_datatype.py index a3ed5bb86414..5937e5c5b091 100644 --- a/py-polars/polars/functions/as_datatype.py +++ b/py-polars/polars/functions/as_datatype.py @@ -598,7 +598,7 @@ def struct( pyexprs = parse_into_list_of_expressions(*exprs, **named_exprs) if schema: - if not exprs: + if not exprs and not named_exprs: # no columns or expressions provided; create one from schema keys expr = wrap_expr( plr.as_struct(parse_into_list_of_expressions(list(schema.keys()))) diff --git a/py-polars/tests/unit/datatypes/test_struct.py b/py-polars/tests/unit/datatypes/test_struct.py index eea22ee8f277..2d7b05916d17 100644 --- a/py-polars/tests/unit/datatypes/test_struct.py +++ b/py-polars/tests/unit/datatypes/test_struct.py @@ -970,3 +970,11 @@ def test_struct_out_nullability_from_arrow() -> None: def test_empty_struct_raise() -> None: with pytest.raises(ValueError): pl.struct() + + +def test_named_exprs() -> None: + df = pl.DataFrame({"a": 1}) + schema = {"b": pl.Int64} + res = df.select(pl.struct(schema=schema, b=pl.col("a"))) + expected = df.select(pl.struct(pl.col("a").alias("b"), schema=schema)) + assert_frame_equal(res, expected)