Skip to content

Fix .transform crash when SeriesGroupBy is empty (#26208) #26228

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 11 commits into from
May 15, 2019
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ Groupby/Resample/Rolling
- Bug in :meth:`pandas.core.groupby.GroupBy.idxmax` and :meth:`pandas.core.groupby.GroupBy.idxmin` with datetime column would return incorrect dtype (:issue:`25444`, :issue:`15306`)
- Bug in :meth:`pandas.core.groupby.GroupBy.cumsum`, :meth:`pandas.core.groupby.GroupBy.cumprod`, :meth:`pandas.core.groupby.GroupBy.cummin` and :meth:`pandas.core.groupby.GroupBy.cummax` with categorical column having absent categories, would return incorrect result or segfault (:issue:`16771`)
- Bug in :meth:`pandas.core.groupby.GroupBy.nth` where NA values in the grouping would return incorrect results (:issue:`26011`)
- Bug in :meth:`pandas.core.groupby.SeriesGroupBy.transform` where transforming an empty group would raise error (:issue:`26208`)


Reshaping
Expand Down
8 changes: 6 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -916,8 +916,12 @@ def transform(self, func, *args, **kwargs):
s = klass(res, indexer)
results.append(s)

from pandas.core.reshape.concat import concat
result = concat(results).sort_index()
# check for empty "results" to avoid concat ValueError
if results:
from pandas.core.reshape.concat import concat
result = concat(results).sort_index()
else:
result = Series()

# we will only try to coerce the result type if
# we have a numeric dtype, as these are *always* udfs
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/groupby/test_grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,23 @@ def test_list_grouper_with_nat(self):
expected = {pd.Timestamp('2011-01-01'): 365}
tm.assert_dict_equal(result.groups, expected)

@pytest.mark.parametrize(
'func,expected',
[
('transform', pd.Series(name=2, index=pd.RangeIndex(0, 0, 1))),
('agg', pd.Series(name=2, index=pd.Float64Index([], name=1))),
('apply', pd.Series(name=2, index=pd.Float64Index([], name=1))),
])
def test_evaluate_with_empty_groups(self, func, expected):
# 26208
# test transform'ing empty groups
# (not testing other agg fns, because they return
# different index objects.
df = pd.DataFrame({1: [], 2: []})
g = df.groupby(1)
result = getattr(g[2], func)(lambda x: x)
assert_series_equal(result, expected)


# get_group
# --------------------------------
Expand Down