Skip to content
Open
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
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ All warnings for upcoming changes in pandas will have the base class :class:`pan

Other enhancements
^^^^^^^^^^^^^^^^^^
- :class:`pandas.NamedAgg` now forwards any ``*args`` and ``**kwargs``
to calls of ``aggfunc`` (:issue:`58283`)
- :func:`pandas.merge` propagates the ``attrs`` attribute to the result if all
inputs have identical ``attrs``, as has so far already been the case for
:func:`pandas.concat`.
Expand Down
59 changes: 52 additions & 7 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
TYPE_CHECKING,
Any,
Literal,
NamedTuple,
Self,
TypeAlias,
TypeVar,
cast,
Expand Down Expand Up @@ -113,11 +113,11 @@


@set_module("pandas")
class NamedAgg(NamedTuple):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems too breaking. Previously, users could access NamedAgg.column after creation, but not if we inherit from tuple. Can we use a dataclass here instead:

@dataclasses.dataclass
class NamedAgg:
    column: Hashable
    aggfunc: AggScalar
    args: tuple = ()
    kwargs: dict = dataclasses.field(default_factory=dict)

    def __init__(self, column: Hashable, aggfunc: AggScalar, *args, **kwargs) -> None:
        self.column = column
        self.aggfunc = aggfunc
        self.args = args
        self.kwargs = kwargs

    def __getitem__(self, key: int):
        if key == 0:
            return self.column
        elif key == 1:
            return self.aggfunc
        elif key == 2:
            return self.args
        elif key == 3:
            return self.kwargs
        raise IndexError("index out of range")

We could then possibly deprecate __getitem__ access.

class NamedAgg(tuple):
"""
Helper for column specific aggregation with control over output column names.

Subclass of typing.NamedTuple.
Subclass of tuple.

Parameters
----------
Expand All @@ -126,26 +126,71 @@ class NamedAgg(NamedTuple):
aggfunc : function or str
Function to apply to the provided column. If string, the name of a built-in
pandas function.
*args, **kwargs :
Optional positional and keyword arguments passed to ``aggfunc``.

See Also
--------
DataFrame.groupby : Group DataFrame using a mapper or by a Series of columns.

Examples
--------
>>> df = pd.DataFrame({"key": [1, 1, 2], "a": [-1, 0, 1], 1: [10, 11, 12]})
>>> df = pd.DataFrame({"key": [1, 1, 2], "a": [-1, 0, 1], "b": [10, 11, 12]})
>>> agg_a = pd.NamedAgg(column="a", aggfunc="min")
>>> agg_1 = pd.NamedAgg(column=1, aggfunc=lambda x: np.mean(x))
>>> df.groupby("key").agg(result_a=agg_a, result_1=agg_1)
result_a result_1
>>> agg_b = pd.NamedAgg(column="b", aggfunc=lambda x: x.mean())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the point here is to demonstrate that you can used a named tuple on columns that are not strings.

>>> df.groupby("key").agg(result_a=agg_a, result_b=agg_b)
result_a result_b
key
1 -1 10.5
2 1 12.0

>>> def n_between(ser, low, high, **kwargs):
... return ser.between(low, high, **kwargs).sum()

>>> agg_between = pd.NamedAgg("a", n_between, 0, 1)
>>> df.groupby("key").agg(count_between=agg_between)
count_between
key
1 1
2 1

>>> agg_between_kw = pd.NamedAgg("a", n_between, 0, 1, inclusive="both")
>>> df.groupby("key").agg(count_between_kw=agg_between_kw)
count_between_kw
key
1 1
2 1
"""

column: Hashable
aggfunc: AggScalar

__slots__ = ()

def __new__(
cls,
column: Hashable,
aggfunc: Callable[..., Any] | str,
*args: Any,
**kwargs: Any,
) -> Self:
if (
callable(aggfunc)
and not getattr(aggfunc, "_is_wrapped", False)
and (args or kwargs)
):
original_func = aggfunc

def wrapped(*call_args: Any, **call_kwargs: Any) -> Any:
series = call_args[0]
final_args = call_args[1:] + args
final_kwargs = {**kwargs, **call_kwargs}
return original_func(series, *final_args, **final_kwargs)

wrapped._is_wrapped = True # type: ignore[attr-defined]
aggfunc = wrapped
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In line with the above, this changes the aggfunc which is a public attribute. Instead, I think we should utilize args/kwargs in places within pandas that accept a NamedAgg

return super().__new__(cls, (column, aggfunc))


@set_module("pandas.api.typing")
class SeriesGroupBy(GroupBy[Series]):
Expand Down
51 changes: 51 additions & 0 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,57 @@ def test_agg_namedtuple(self):
expected = df.groupby("A").agg(b=("B", "sum"), c=("B", "count"))
tm.assert_frame_equal(result, expected)

def n_between(self, ser, low, high, **kwargs):
return ser.between(low, high, **kwargs).sum()

def test_namedagg_args(self):
df = DataFrame({"A": [0, 0, 1, 1], "B": [-1, 0, 1, 2]})

result = df.groupby("A").agg(
count_between=pd.NamedAgg("B", self.n_between, 0, 1)
)
expected = DataFrame({"count_between": [1, 1]}, index=Index([0, 1], name="A"))
tm.assert_frame_equal(result, expected)

def test_namedagg_kwargs(self):
df = DataFrame({"A": [0, 0, 1, 1], "B": [-1, 0, 1, 2]})

result = df.groupby("A").agg(
count_between_kw=pd.NamedAgg("B", self.n_between, 0, 1, inclusive="both")
)
expected = DataFrame(
{"count_between_kw": [1, 1]}, index=Index([0, 1], name="A")
)
tm.assert_frame_equal(result, expected)

def test_namedagg_args_and_kwargs(self):
df = DataFrame({"A": [0, 0, 1, 1], "B": [-1, 0, 1, 2]})

result = df.groupby("A").agg(
count_between_mix=pd.NamedAgg(
"B", self.n_between, 0, 1, inclusive="neither"
)
)
expected = DataFrame(
{"count_between_mix": [0, 0]}, index=Index([0, 1], name="A")
)
tm.assert_frame_equal(result, expected)

def test_multiple_named_agg_with_args_and_kwargs(self):
df = DataFrame({"A": [0, 1, 2, 3], "B": [1, 2, 3, 4]})

result = df.groupby("A").agg(
n_between01=pd.NamedAgg("B", self.n_between, 0, 1),
n_between13=pd.NamedAgg("B", self.n_between, 1, 3),
n_between02=pd.NamedAgg("B", self.n_between, 0, 2),
)
expected = df.groupby("A").agg(
n_between01=("B", lambda x: x.between(0, 1).sum()),
n_between13=("B", lambda x: x.between(0, 3).sum()),
n_between02=("B", lambda x: x.between(0, 2).sum()),
)
tm.assert_frame_equal(result, expected)

def test_mangled(self):
df = DataFrame({"A": [0, 1], "B": [1, 2], "C": [3, 4]})
result = df.groupby("A").agg(b=("B", lambda x: 0), c=("C", lambda x: 1))
Expand Down
Loading