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 2 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
14 changes: 9 additions & 5 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,18 +844,22 @@ 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 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])
try:
# 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])
Copy link
Member

Choose a reason for hiding this comment

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

Should the try/except IndexError only be for data.iloc[:0]? A user's f could throw an IndexError which we don't necessarily want to capture here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Do we have a test that could demonstrate such an instance? I am having a little bit of an issue coming up with one.

Copy link
Member

Choose a reason for hiding this comment

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

Maybe a UDF like:

def f(group):
   raise IndexError

Should still raise the IndexError and got be caught by this try/except?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In version 1.3.5 before this PR #44092 was merged. The IndexError will not be raised (I just tested it out).

I believe the idea was that, regardless of the UD function, if the groupby has no groups then an empty dataframe is always returned.

Copy link
Member

Choose a reason for hiding this comment

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

Okay. Nonetheless, if we know data is empty and .iloc[:0] will raise an IndexError, it might be more explicit to use

if not data.empty:
    f(data.iloc[:0])

I just want to avoid any unintended side effects of except IndexError catching the exception from f and not data.iloc[:0]

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Awesome idea. Will try it out.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

using not data.empty fails the tests for #44092.

Copy link
Member

Choose a reason for hiding this comment

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

Which one in particular?

Copy link
Member

@rhshadrach rhshadrach Sep 19, 2022

Choose a reason for hiding this comment

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

I don't believe data.iloc[:0] should ever raise on any frame; is there an example where it does?

I do think we need to decide a general pattern of behavior for pandas methods that take a UDF and operate on an empty frame. I'm planning on putting a proposal together but it will be some time (maybe a week or two). In the mean time, it seems to me catching some error types like IndexError but not others might be confusing for users. I believe this code was added in #44092 (cc @jbrockmendel) to handle cases where apply was called with a pandas method (e.g. "skew"). Can we instead add this block to just those particular methods?

Copy link
Member

Choose a reason for hiding this comment

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

Can we instead add this block to just those particular methods?

Works for me.

except IndexError:
# If IndexError is raised,
# maintain consistency for all operations on empty groups
pass

return result_values, mutated

Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1331,3 +1331,13 @@ def test_result_name_when_one_group(name):
expected = Series([1, 2], name=name)

tm.assert_series_equal(result, expected)


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

# Both operations should return an empty series instead of IndexError for apply UDF
result = empty_df.groupby("a").b.apply(lambda x: x.values[-1])
expected = empty_df.groupby("a").b.agg("sum")

tm.assert_series_equal(result, expected)