Skip to content

Commit

Permalink
fix : strict parameter is enabled by default
Browse files Browse the repository at this point in the history
  • Loading branch information
= committed Nov 5, 2024
1 parent 047e578 commit 07155cf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
10 changes: 7 additions & 3 deletions py-polars/polars/expr/struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,16 @@ 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.
Parameters
----------
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
--------
Expand All @@ -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]} │
└──────────────────────┘
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -332,7 +336,7 @@ def with_fields(
│ 1.0 ┆ 4 ┆ 40 ┆ 10 │
│ 2.0 ┆ 9 ┆ 18 ┆ 2 │
│ 3.0 ┆ 16 ┆ 48 ┆ 3 │
└─────┴─────┴──────┴─────────┘
└─────┴─────┴──���────┴───���──────┘
Parameters
----------
Expand Down
13 changes: 7 additions & 6 deletions py-polars/polars/series/struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,24 +73,25 @@ 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.
Parameters
----------
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:
Expand Down

0 comments on commit 07155cf

Please sign in to comment.