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 @@ -391,6 +391,7 @@ Groupby/Resample/Rolling
- Bug in :meth:`pandas.core.window.Rolling.min` and :meth:`pandas.core.window.Rolling.max` that caused a memory leak (:issue:`25893`)
- 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.SeriesGroupBy.transform` where transforming an empty SeriesGroupBy would raise error. Now returns empty Series, just like .apply and .agg. (:issue:`26208`)


Reshaping
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -917,8 +917,11 @@ 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()
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
10 changes: 10 additions & 0 deletions pandas/tests/groupby/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,3 +880,13 @@ def test_transform_absent_categories(func):
result = getattr(df.y.groupby(df.x), func)()
expected = df.y
assert_series_equal(result, expected)


def test_transform_empty_df():
# 26208
# handle empty SeriesGroupBy
d = pd.DataFrame({1: [], 2: []})
g = d.groupby(1)
result = g[2].transform(lambda x: x)
expected = pd.Series([], name=2)
assert_series_equal(result, expected)