Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking β€œSign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: raise informative error message when grouping by expressions #1677

Merged
merged 2 commits into from
Dec 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions narwhals/dataframe.py
Original file line number Diff line number Diff line change
@@ -2209,9 +2209,18 @@ def group_by(
β”‚ c ┆ 3 ┆ 1 β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
"""
from narwhals.expr import Expr
from narwhals.group_by import GroupBy
from narwhals.series import Series

return GroupBy(self, *flatten(keys), drop_null_keys=drop_null_keys)
flat_keys = flatten(keys)
if any(isinstance(x, (Expr, Series)) for x in flat_keys):
msg = (
"`group_by` with expression or Series keys is not (yet?) supported.\n\n"
"Hint: instead of `df.group_by(nw.col('a'))`, use `df.group_by('a')`."
)
raise NotImplementedError(msg)
return GroupBy(self, *flat_keys, drop_null_keys=drop_null_keys)

def sort(
self,
@@ -4444,9 +4453,18 @@ def group_by(
β”‚ c ┆ 3 ┆ 1 β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
"""
from narwhals.expr import Expr
from narwhals.group_by import LazyGroupBy
from narwhals.series import Series

return LazyGroupBy(self, *flatten(keys), drop_null_keys=drop_null_keys)
flat_keys = flatten(keys)
if any(isinstance(x, (Expr, Series)) for x in flat_keys):
msg = (
"`group_by` with expression or Series keys is not (yet?) supported.\n\n"
"Hint: instead of `df.group_by(nw.col('a'))`, use `df.group_by('a')`."
)
raise NotImplementedError(msg)
return LazyGroupBy(self, *flat_keys, drop_null_keys=drop_null_keys)

def sort(
self,
6 changes: 6 additions & 0 deletions tests/group_by_test.py
Original file line number Diff line number Diff line change
@@ -453,3 +453,9 @@ def test_all_kind_of_aggs(
"i": [3, 2],
}
assert_equal_data(result, expected)


def test_group_by_expr(constructor: Constructor) -> None:
df = nw.from_native(constructor({"a": [1, 1, 3], "b": [4, 5, 6]}))
with pytest.raises(NotImplementedError, match=r"not \(yet\?\) supported"):
df.group_by(nw.col("a")).agg(nw.col("b").mean()) # type: ignore[arg-type]
Loading