Skip to content

Commit

Permalink
feat: Raise informative error message if non-IntoExpr is passed by na…
Browse files Browse the repository at this point in the history
…me in *Frame.group_by (#17654)
  • Loading branch information
MarcoGorelli authored Jul 16, 2024
1 parent 08b6f1d commit ecddc13
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5741,6 +5741,16 @@ def group_by(
│ c ┆ 3 ┆ 1 │
└─────┴─────┴─────┘
"""
for _key, value in named_by.items():
if not isinstance(value, (str, pl.Expr, pl.Series)):
msg = (
f"Expected Polars expression or object convertible to one, got {type(value)}.\n\n"
"Hint: if you tried\n"
f" group_by(by={value!r})\n"
"then you probably want to use this instead:\n"
f" group_by({value!r})"
)
raise TypeError(msg)
return GroupBy(self, *by, **named_by, maintain_order=maintain_order)

@deprecate_renamed_parameter("by", "group_by", version="0.20.14")
Expand Down
10 changes: 10 additions & 0 deletions py-polars/polars/lazyframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3357,6 +3357,16 @@ def group_by(
│ c ┆ 1 ┆ 1.0 │
└─────┴─────┴─────┘
"""
for _key, value in named_by.items():
if not isinstance(value, (str, pl.Expr, pl.Series)):
msg = (
f"Expected Polars expression or object convertible to one, got {type(value)}.\n\n"
"Hint: if you tried\n"
f" group_by(by={value!r})\n"
"then you probably want to use this instead:\n"
f" group_by({value!r})"
)
raise TypeError(msg)
exprs = parse_into_list_of_expressions(*by, **named_by)
lgb = self._ldf.group_by(exprs, maintain_order)
return LazyGroupBy(lgb)
Expand Down
7 changes: 7 additions & 0 deletions py-polars/tests/unit/operations/test_group_by.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,3 +1139,10 @@ def test_grouped_slice_literals() -> None:
), # slices a list of 1 element, so remains the same element
x2=pl.lit(pl.Series([1, 2])).slice(-1, 1),
).to_dict(as_series=False) == {"literal": [True], "x": [[1, 2]], "x2": [2]}


def test_positional_by_with_list_or_tuple_17540() -> None:
with pytest.raises(TypeError, match="Hint: if you"):
pl.DataFrame({"a": [1, 2, 3]}).group_by(by=["a"])
with pytest.raises(TypeError, match="Hint: if you"):
pl.LazyFrame({"a": [1, 2, 3]}).group_by(by=["a"])

0 comments on commit ecddc13

Please sign in to comment.