Skip to content

BUG: DataFrame.agg not returning a reduced result when providing a lambda #53208

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

Closed
wants to merge 1 commit into from
Closed
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/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,7 @@ Plotting

Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
- Bug in :meth:`DataFrame.agg` when providing a dict-like or tuple-like renaming argument with a ``lambda`` function (:issue:`41768`)
- Bug in :meth:`DataFrame.resample` and :meth:`Series.resample` in incorrectly allowing non-fixed ``freq`` when resampling on a :class:`TimedeltaIndex` (:issue:`51896`)
- Bug in :meth:`DataFrameGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmax` return wrong dtype when used on empty DataFrameGroupBy or SeriesGroupBy (:issue:`51423`)
- Bug in weighted rolling aggregations when specifying ``min_periods=0`` (:issue:`51449`)
Expand Down
7 changes: 7 additions & 0 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from pandas.core.dtypes.common import (
is_dict_like,
is_list_like,
is_scalar,
is_sequence,
)
from pandas.core.dtypes.dtypes import (
Expand Down Expand Up @@ -1100,9 +1101,15 @@ def agg(self):
# operation is actually defined on the Series, e.g. str
try:
result = self.obj.apply(f)
# GH 41768: Attempt to return a reduced result
if not is_scalar(result):
result = f(self.obj)
except (ValueError, AttributeError, TypeError):
result = f(self.obj)

# TODO: Shouldn't we validate this returns a scalar?
# Would fail test_agg_listlike_result, test_agg_transform

return result

def apply_empty_result(self) -> Series:
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/apply/test_frame_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1515,3 +1515,24 @@ def test_agg_dist_like_and_nonunique_columns():
result = df.agg({"A": "count"})
expected = df["A"].count()
tm.assert_series_equal(result, expected)


def test_agg_lambda_tuple_result_rename():
# GH 41768
df = DataFrame(
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [np.nan, np.nan, np.nan]],
columns=["A", "B", "C"],
)
result = df.agg(z=("C", lambda x: np.mean(x)))
expected = DataFrame([6.0], index=["z"], columns=["C"])
tm.assert_frame_equal(result, expected)


def test_agg_dictlike_lambda():
df = DataFrame(
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [np.nan, np.nan, np.nan]],
columns=["A", "B", "C"],
)
result = df.agg({"C": lambda x: np.mean(x)})
expected = Series([6.0], index=["C"])
tm.assert_series_equal(result, expected)