From 07155cfa5302b78140e2bad5ac55ca8e6ed59752 Mon Sep 17 00:00:00 2001 From: = <=> Date: Tue, 5 Nov 2024 15:17:08 +0100 Subject: [PATCH] fix : strict parameter is enabled by default --- py-polars/polars/expr/struct.py | 10 +++++++--- py-polars/polars/series/struct.py | 13 +++++++------ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/py-polars/polars/expr/struct.py b/py-polars/polars/expr/struct.py index 1df3a16f4411..2ee60c0f39bf 100644 --- a/py-polars/polars/expr/struct.py +++ b/py-polars/polars/expr/struct.py @@ -189,7 +189,7 @@ def unnest(self) -> Expr: """ return self.field("*") - def rename_fields(self, names: Sequence[str]) -> Expr: + def rename_fields(self, names: Sequence[str], strict: bool = True) -> Expr: """ Rename the fields of the struct. @@ -197,6 +197,8 @@ def rename_fields(self, names: Sequence[str]) -> Expr: ---------- names New names, given in the same order as the struct's fields. + strict + If True, raises an error if the length of names does not match the number of fields. Examples -------- @@ -214,7 +216,7 @@ def rename_fields(self, names: Sequence[str]) -> Expr: │ struct_col │ │ --- │ │ struct[4] │ - ╞══════════════════════╡ + ╞══════��═══════════════╡ │ {1,"ab",true,[1, 2]} │ │ {2,"cd",null,[3]} │ └──────────────────────┘ @@ -251,6 +253,8 @@ def rename_fields(self, names: Sequence[str]) -> Expr: >>> df.select(pl.col("struct_col").struct.field("aaa")) # doctest: +SKIP StructFieldNotFoundError: aaa """ + if strict and len(names) != len(self.fields): + raise ValueError("The length of names must match the number of fields in the struct.") return wrap_expr(self._pyexpr.struct_rename_fields(names)) def json_encode(self) -> Expr: @@ -332,7 +336,7 @@ def with_fields( │ 1.0 ┆ 4 ┆ 40 ┆ 10 │ │ 2.0 ┆ 9 ┆ 18 ┆ 2 │ │ 3.0 ┆ 16 ┆ 48 ┆ 3 │ - └─────┴─────┴───────┴──────────┘ + └─────┴─────┴──���────┴───���──────┘ Parameters ---------- diff --git a/py-polars/polars/series/struct.py b/py-polars/polars/series/struct.py index a04d254808d3..8b89f631f610 100644 --- a/py-polars/polars/series/struct.py +++ b/py-polars/polars/series/struct.py @@ -73,7 +73,7 @@ def field(self, name: str) -> Series: ] """ - def rename_fields(self, names: Sequence[str]) -> Series: + def rename_fields(self, names: Sequence[str], strict: bool = True) -> Series: """ Rename the fields of the struct. @@ -81,16 +81,17 @@ def rename_fields(self, names: Sequence[str]) -> Series: ---------- names New names in the order of the struct's fields. + strict + If True, raises an error if the length of names does not match the number of fields. Examples -------- >>> s = pl.Series([{"a": 1, "b": 2}, {"a": 3, "b": 4}]) - >>> s.struct.fields - ['a', 'b'] - >>> s = s.struct.rename_fields(["c", "d"]) - >>> s.struct.fields - ['c', 'd'] + >>> s.struct.rename_fields(["c", "d"], strict=True) """ + if strict and len(names) != len(self.fields): + raise ValueError("The length of names must match the number of fields in the struct.") + @property def schema(self) -> Schema: