Skip to content

BUG: Fix agg ingore arg/kwargs when given list like func #50863

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
Show file tree
Hide file tree
Changes from 4 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
82 changes: 73 additions & 9 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,20 @@ def __init__(
self.result_type = result_type

# curry if needed
if (
(kwargs or args)
and not isinstance(func, (np.ufunc, str))
and not is_list_like(func)
):

def f(x):
return func(x, *args, **kwargs)

if (kwargs or args) and not isinstance(func, (np.ufunc, str)):
if not is_list_like(func):

def f(x):
return func(x, *args, **kwargs)

elif type(func) == list and all(i for i in func if callable(i)):
# GH 50624
# only explicit arg passing is supported temporarily
# eg. df.agg([foo], a=1)
# df.agg([foo], 1) is not supported
f = _recreate_func(func, kwargs)
else:
f = func
else:
f = func

Expand Down Expand Up @@ -1506,3 +1511,62 @@ def validate_func_kwargs(
no_arg_message = "Must provide 'func' or named aggregation **kwargs."
raise TypeError(no_arg_message)
return columns, func


def _check_arg(callable: Callable, arg: str) -> bool:
# GH 50624
"""To check if arg is a valid argument for callable.

Parameters
----------
callable : Callable
arg : str

Returns
-------
bool

Examples
--------
>>> def func(x, a=1, b=2):
... pass
>>> _check_arg(func, 'a')
True
"""
argspec = inspect.getfullargspec(callable)
args_names = argspec.args + argspec.kwonlyargs
return arg in args_names


def _recreate_func(
callable_list: list[Callable], kwargs: dict
) -> list[partial[Any]] | Callable[[Any], Any]:
# GH 50624
"""Recreate callable with kwargs.

Parameters
----------
callable_list : list[Callable]
kwargs : dict

Returns
-------
list[partial[Any]] | Callable[[Any], Any]

Examples
--------
>>> def func(x, a=1, b=2):
... pass
>>> _recreate_func([func], {'a': 3, 'b': 4})
[<functools.partial object at 0x...>, a=3, b=4]
"""
func_kwargs = {}
for single_func in callable_list:
single_func_kwargs = {
k: v for k, v in kwargs.items() if _check_arg(single_func, k)
}
func_kwargs[single_func] = single_func_kwargs

return [
partial(single_func, **kwargs) for single_func, kwargs in func_kwargs.items()
]
19 changes: 19 additions & 0 deletions pandas/tests/apply/test_frame_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1623,3 +1623,22 @@ def test_any_apply_keyword_non_zero_axis_regression():

result = df.apply("any", 1)
tm.assert_series_equal(result, expected)


def test_agg_list_like_arg():
# GH 50624
df = DataFrame({"x": [1, 2, 3]})

def foo1(x, a=1, b=2):
return x + a + b

def foo2(x, c=3, d=4):
return x + c + d

result = df.agg([foo1, foo2], 0, a=5, b=6, c=7, d=8)
expected = DataFrame(
[[12, 16], [13, 17], [14, 18]],
columns=MultiIndex.from_tuples([("x", "foo1"), ("x", "foo2")]),
index=[0, 1, 2],
)
tm.assert_frame_equal(result, expected)