Skip to content

Commit f656fb3

Browse files
authored
feat: raise informative error message when grouping by expressions (#1677)
* raise informative error message when grouping by expressions * add hint
1 parent 20539cb commit f656fb3

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

narwhals/dataframe.py

+20-2
Original file line numberDiff line numberDiff line change
@@ -2209,9 +2209,18 @@ def group_by(
22092209
│ c ┆ 3 ┆ 1 │
22102210
└─────┴─────┴─────┘
22112211
"""
2212+
from narwhals.expr import Expr
22122213
from narwhals.group_by import GroupBy
2214+
from narwhals.series import Series
22132215

2214-
return GroupBy(self, *flatten(keys), drop_null_keys=drop_null_keys)
2216+
flat_keys = flatten(keys)
2217+
if any(isinstance(x, (Expr, Series)) for x in flat_keys):
2218+
msg = (
2219+
"`group_by` with expression or Series keys is not (yet?) supported.\n\n"
2220+
"Hint: instead of `df.group_by(nw.col('a'))`, use `df.group_by('a')`."
2221+
)
2222+
raise NotImplementedError(msg)
2223+
return GroupBy(self, *flat_keys, drop_null_keys=drop_null_keys)
22152224

22162225
def sort(
22172226
self,
@@ -4444,9 +4453,18 @@ def group_by(
44444453
│ c ┆ 3 ┆ 1 │
44454454
└─────┴─────┴─────┘
44464455
"""
4456+
from narwhals.expr import Expr
44474457
from narwhals.group_by import LazyGroupBy
4458+
from narwhals.series import Series
44484459

4449-
return LazyGroupBy(self, *flatten(keys), drop_null_keys=drop_null_keys)
4460+
flat_keys = flatten(keys)
4461+
if any(isinstance(x, (Expr, Series)) for x in flat_keys):
4462+
msg = (
4463+
"`group_by` with expression or Series keys is not (yet?) supported.\n\n"
4464+
"Hint: instead of `df.group_by(nw.col('a'))`, use `df.group_by('a')`."
4465+
)
4466+
raise NotImplementedError(msg)
4467+
return LazyGroupBy(self, *flat_keys, drop_null_keys=drop_null_keys)
44504468

44514469
def sort(
44524470
self,

tests/group_by_test.py

+6
Original file line numberDiff line numberDiff line change
@@ -453,3 +453,9 @@ def test_all_kind_of_aggs(
453453
"i": [3, 2],
454454
}
455455
assert_equal_data(result, expected)
456+
457+
458+
def test_group_by_expr(constructor: Constructor) -> None:
459+
df = nw.from_native(constructor({"a": [1, 1, 3], "b": [4, 5, 6]}))
460+
with pytest.raises(NotImplementedError, match=r"not \(yet\?\) supported"):
461+
df.group_by(nw.col("a")).agg(nw.col("b").mean()) # type: ignore[arg-type]

0 commit comments

Comments
 (0)