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 4 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 @@ -845,15 +845,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
28 changes: 28 additions & 0 deletions pandas/tests/groupby/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -1331,3 +1331,31 @@ 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", group_keys=True).b.apply(lambda x: x.values[-1])
Copy link
Member

Choose a reason for hiding this comment

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

Could you compare both of these results to an actual empty Series? Just in case a code change returns the same, incorrect result for both result and expected

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@mroeschke I am having an issue equating it to an empty series.

    # GIVEN
    empty_series = Series([], name="b")
    empty_series.index.astype(np.float64)

    tm.assert_series_equal(result, empty_series)

Returns

left = Float64Index([], dtype='float64', name='a'), right = RangeIndex(start=0, stop=0, step=1), obj = 'Series.index'

    def _check_types(left, right, obj="Index") -> None:
        if not exact:
            return
    
        assert_class_equal(left, right, exact=exact, obj=obj)
>       assert_attr_equal("inferred_type", left, right, obj=obj)
E       AssertionError: Series.index are different
E       
E       Attribute "inferred_type" are different
E       [left]:  floating
E       [right]: integer

How do I create an empty series that equals result?

Copy link
Member

Choose a reason for hiding this comment

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

In [8]: ser = pd.Series([], name="b", dtype="float64", index=pd.Index([], dtype="float64", name="a"))

In [9]: ser.index
Out[9]: Float64Index([], dtype='float64', name='a')

expected = empty_df.groupby("a", group_keys=True).b.agg("sum")

tm.assert_series_equal(result, expected)


@pytest.mark.parametrize(
"error_type",
[
TypeError,
ValueError,
IndexError,
],
)
def test_udf_raise_error_on_empty_df(error_type):
empty_df = DataFrame({"a": [], "b": []})

def f(group):
raise error_type

# Exception should not be raised.
Copy link
Member

Choose a reason for hiding this comment

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

I would expect the exception in f to actually raise in this case.

Since this isn't directly related the original issue, maybe this can be addressed later.

empty_df.groupby("a", group_keys=True).b.apply(f)
Copy link
Member

Choose a reason for hiding this comment

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

Could you assert the result of this operation?