Skip to content

Backport PR #32121 on branch 1.0.x (REG: dont call func on empty input) #32159

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
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.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Fixed regressions
- Fixed regression in :meth:`rolling(..).corr() <pandas.core.window.Rolling.corr>` when using a time offset (:issue:`31789`)
- Fixed regression where :func:`read_pickle` raised a ``UnicodeDecodeError`` when reading a py27 pickle with :class:`MultiIndex` column (:issue:`31988`).
- Fixed regression in :class:`DataFrame` arithmetic operations with mis-matched columns (:issue:`31623`)
- Fixed regression in :meth:`GroupBy.agg` calling a user-provided function an extra time on an empty input (:issue:`31760`)
-

.. ---------------------------------------------------------------------------
Expand Down
11 changes: 2 additions & 9 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -923,17 +923,10 @@ def _python_agg_general(self, func, *args, **kwargs):

try:
# if this function is invalid for this dtype, we will ignore it.
func(obj[:0])
result, counts = self.grouper.agg_series(obj, f)
except TypeError:
continue
except AssertionError:
raise
except Exception:
# Our function depends on having a non-empty argument
# See test_groupby_agg_err_catching
pass

result, counts = self.grouper.agg_series(obj, f)

assert result is not None
key = base.OutputKey(label=name, position=idx)
output[key] = self._try_cast(result, obj, numeric_only=True)
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/groupby/aggregate/test_aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@
from pandas.core.groupby.grouper import Grouping


def test_groupby_agg_no_extra_calls():
# GH#31760
df = pd.DataFrame({"key": ["a", "b", "c", "c"], "value": [1, 2, 3, 4]})
gb = df.groupby("key")["value"]

def dummy_func(x):
assert len(x) != 0
return x.sum()

gb.agg(dummy_func)


def test_agg_regression1(tsframe):
grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month])
result = grouped.agg(np.mean)
Expand Down