Skip to content

BUG: Fix calling groupBy(...).apply(func) on an empty dataframe invokes func #48579

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 15 commits into from
Sep 27, 2022
Merged
Show file tree
Hide file tree
Changes from 8 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
13 changes: 6 additions & 7 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -787,15 +787,14 @@ def apply(
if not mutated and not _is_indexed_like(res, group_axes, axis):
mutated = True
result_values.append(res)

# getattr pattern for __name__ is needed for functools.partial objects
if len(group_keys) == 0 and getattr(f, "__name__", None) not in [
"idxmin",
"idxmax",
"nanargmin",
"nanargmax",
if len(group_keys) == 0 and getattr(f, "__name__", None) in [
"mad",
"skew",
"sum",
"prod",
]:
# If group_keys is empty, then no function calls have been made,
# If group_keys is empty, then no function calls have been made,
# so we will not have raised even if this is an invalid dtype.
# So do one dummy call here to raise appropriate TypeError.
f(data.iloc[:0])
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1331,3 +1331,19 @@ def test_result_name_when_one_group(name):
expected = Series([1, 2], name=name)

tm.assert_series_equal(result, expected)


def test_empty_df():
# GH 47985
empty_df = DataFrame({"a": [], "b": []})

# Both operations should return an empty series instead of IndexError for apply UDF
result1 = empty_df.groupby("a", group_keys=True).b.apply(lambda x: x.values[-1])
result2 = empty_df.groupby("a", group_keys=True).b.agg("sum")
Copy link
Member

Choose a reason for hiding this comment

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

Can you parametrize this instead - e.g. have ("apply", lambda x: x.values[-1]) and ("agg", "sum") as the method / op parameters and do

gb = empty_df.groupby("a", group_keys=True)
result = getattr(gb, method)(op)

This allows developers to debug more easily in the future. The common case you can run into is setting a break point within the code for a test that consists of multiple tests. That break point can then be hit by the successful tests as well as the one that is failing, making debugging more difficult.

By using pytest's parametrize, one can just run the failing test.


expected = Series(
[], name="b", dtype="float64", index=Index([], dtype="float64", name="a")
)

tm.assert_series_equal(result1, expected)
tm.assert_series_equal(result2, expected)