Skip to content

Commit ff4437e

Browse files
HHestjreback
authored andcommitted
Fix .transform crash when SeriesGroupBy is empty (#26208) (#26228)
1 parent 5468cc0 commit ff4437e

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

doc/source/whatsnew/v0.25.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,7 @@ Groupby/Resample/Rolling
440440
- 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`)
441441
- 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`)
442442
- Bug in :meth:`pandas.core.groupby.GroupBy.nth` where NA values in the grouping would return incorrect results (:issue:`26011`)
443+
- Bug in :meth:`pandas.core.groupby.SeriesGroupBy.transform` where transforming an empty group would raise error (:issue:`26208`)
443444

444445

445446
Reshaping

pandas/core/groupby/generic.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -916,8 +916,12 @@ def transform(self, func, *args, **kwargs):
916916
s = klass(res, indexer)
917917
results.append(s)
918918

919-
from pandas.core.reshape.concat import concat
920-
result = concat(results).sort_index()
919+
# check for empty "results" to avoid concat ValueError
920+
if results:
921+
from pandas.core.reshape.concat import concat
922+
result = concat(results).sort_index()
923+
else:
924+
result = Series()
921925

922926
# we will only try to coerce the result type if
923927
# we have a numeric dtype, as these are *always* udfs

pandas/tests/groupby/test_grouping.py

+17
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,23 @@ def test_list_grouper_with_nat(self):
552552
expected = {pd.Timestamp('2011-01-01'): 365}
553553
tm.assert_dict_equal(result.groups, expected)
554554

555+
@pytest.mark.parametrize(
556+
'func,expected',
557+
[
558+
('transform', pd.Series(name=2, index=pd.RangeIndex(0, 0, 1))),
559+
('agg', pd.Series(name=2, index=pd.Float64Index([], name=1))),
560+
('apply', pd.Series(name=2, index=pd.Float64Index([], name=1))),
561+
])
562+
def test_evaluate_with_empty_groups(self, func, expected):
563+
# 26208
564+
# test transform'ing empty groups
565+
# (not testing other agg fns, because they return
566+
# different index objects.
567+
df = pd.DataFrame({1: [], 2: []})
568+
g = df.groupby(1)
569+
result = getattr(g[2], func)(lambda x: x)
570+
assert_series_equal(result, expected)
571+
555572

556573
# get_group
557574
# --------------------------------

0 commit comments

Comments
 (0)