Skip to content

Commit

Permalink
feat: raise informative error message if list or tuple is passed to `…
Browse files Browse the repository at this point in the history
…by` in *Frame.group_by
  • Loading branch information
MarcoGorelli committed Jul 16, 2024
1 parent 30bf890 commit ef3fe8d
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 ef3fe8d

Please sign in to comment.