Skip to content

Commit

Permalink
Fix .transform crash when SeriesGroupBy is empty (pandas-dev#26208) (p…
Browse files Browse the repository at this point in the history
  • Loading branch information
HHest authored and jreback committed May 15, 2019
1 parent 5468cc0 commit ff4437e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
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 @@ -440,6 +440,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

0 comments on commit ff4437e

Please sign in to comment.