Skip to content

BUG: Allow passing of args/kwargs to groupby.apply with str func #46481

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

Merged
merged 3 commits into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ Groupby/resample/rolling
- Bug in :meth:`GroupBy.cummin` and :meth:`GroupBy.cummax` with nullable dtypes incorrectly altering the original data in place (:issue:`46220`)
- Bug in :meth:`GroupBy.cummax` with ``int64`` dtype with leading value being the smallest possible int64 (:issue:`46382`)
- Bug in :meth:`GroupBy.max` with empty groups and ``uint64`` dtype incorrectly raising ``RuntimeError`` (:issue:`46408`)
- Bug in :meth:`.GroupBy.apply` would fail when ``func`` was a string and args or kwargs were supplied (:issue:`46479`)
-

Reshaping
Expand Down
26 changes: 13 additions & 13 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1363,10 +1363,19 @@ def apply(self, func, *args, **kwargs) -> NDFrameT:

func = com.is_builtin_func(func)

# this is needed so we don't try and wrap strings. If we could
# resolve functions to their callable functions prior, this
# wouldn't be needed
if args or kwargs:
if isinstance(func, str):
if hasattr(self, func):
res = getattr(self, func)
if callable(res):
return res(*args, **kwargs)
elif args or kwargs:
raise ValueError(f"Cannot pass arguments to property {func}")
return res

else:
raise TypeError(f"apply func should be callable, not '{func}'")

elif args or kwargs:
if callable(func):

@wraps(func)
Expand All @@ -1382,15 +1391,6 @@ def f(g):
raise ValueError(
"func must be a callable if args or kwargs are supplied"
)
elif isinstance(func, str):
if hasattr(self, func):
res = getattr(self, func)
if callable(res):
return res()
return res

else:
raise TypeError(f"apply func should be callable, not '{func}'")
else:

f = func
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1247,3 +1247,12 @@ def test_apply_nonmonotonic_float_index(arg, idx):
expected = DataFrame({"col": arg}, index=idx)
result = expected.groupby("col").apply(lambda x: x)
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize("args, kwargs", [([True], {}), ([], {"numeric_only": True})])
def test_apply_str_with_args(df, args, kwargs):
# GH#46479
gb = df.groupby("A")
result = gb.apply("sum", *args, **kwargs)
expected = gb.sum(numeric_only=True)
tm.assert_frame_equal(result, expected)