Skip to content

Commit 258cfcc

Browse files
authored
BUG: Allow passing of args/kwargs to groupby.apply with str func (#46481)
1 parent d2faa2a commit 258cfcc

File tree

3 files changed

+23
-13
lines changed

3 files changed

+23
-13
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@ Groupby/resample/rolling
527527
- Bug in :meth:`GroupBy.cummin` and :meth:`GroupBy.cummax` with nullable dtypes incorrectly altering the original data in place (:issue:`46220`)
528528
- Bug in :meth:`GroupBy.cummax` with ``int64`` dtype with leading value being the smallest possible int64 (:issue:`46382`)
529529
- Bug in :meth:`GroupBy.max` with empty groups and ``uint64`` dtype incorrectly raising ``RuntimeError`` (:issue:`46408`)
530+
- Bug in :meth:`.GroupBy.apply` would fail when ``func`` was a string and args or kwargs were supplied (:issue:`46479`)
530531
-
531532

532533
Reshaping

pandas/core/groupby/groupby.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -1363,10 +1363,19 @@ def apply(self, func, *args, **kwargs) -> NDFrameT:
13631363

13641364
func = com.is_builtin_func(func)
13651365

1366-
# this is needed so we don't try and wrap strings. If we could
1367-
# resolve functions to their callable functions prior, this
1368-
# wouldn't be needed
1369-
if args or kwargs:
1366+
if isinstance(func, str):
1367+
if hasattr(self, func):
1368+
res = getattr(self, func)
1369+
if callable(res):
1370+
return res(*args, **kwargs)
1371+
elif args or kwargs:
1372+
raise ValueError(f"Cannot pass arguments to property {func}")
1373+
return res
1374+
1375+
else:
1376+
raise TypeError(f"apply func should be callable, not '{func}'")
1377+
1378+
elif args or kwargs:
13701379
if callable(func):
13711380

13721381
@wraps(func)
@@ -1382,15 +1391,6 @@ def f(g):
13821391
raise ValueError(
13831392
"func must be a callable if args or kwargs are supplied"
13841393
)
1385-
elif isinstance(func, str):
1386-
if hasattr(self, func):
1387-
res = getattr(self, func)
1388-
if callable(res):
1389-
return res()
1390-
return res
1391-
1392-
else:
1393-
raise TypeError(f"apply func should be callable, not '{func}'")
13941394
else:
13951395

13961396
f = func

pandas/tests/groupby/test_apply.py

+9
Original file line numberDiff line numberDiff line change
@@ -1247,3 +1247,12 @@ def test_apply_nonmonotonic_float_index(arg, idx):
12471247
expected = DataFrame({"col": arg}, index=idx)
12481248
result = expected.groupby("col").apply(lambda x: x)
12491249
tm.assert_frame_equal(result, expected)
1250+
1251+
1252+
@pytest.mark.parametrize("args, kwargs", [([True], {}), ([], {"numeric_only": True})])
1253+
def test_apply_str_with_args(df, args, kwargs):
1254+
# GH#46479
1255+
gb = df.groupby("A")
1256+
result = gb.apply("sum", *args, **kwargs)
1257+
expected = gb.sum(numeric_only=True)
1258+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)