Skip to content

Commit 2aa4dc0

Browse files
author
Diego Torres Quintanilla
committed
BUG: fix groupby.transform rename bug (#23461)
1 parent 2eef865 commit 2aa4dc0

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1296,6 +1296,7 @@ Groupby/Resample/Rolling
12961296
- :func:`RollingGroupby.agg` and :func:`ExpandingGroupby.agg` now support multiple aggregation functions as parameters (:issue:`15072`)
12971297
- Bug in :meth:`DataFrame.resample` and :meth:`Series.resample` when resampling by a weekly offset (``'W'``) across a DST transition (:issue:`9119`, :issue:`21459`)
12981298
- Bug in :meth:`DataFrame.expanding` in which the ``axis`` argument was not being respected during aggregations (:issue:`23372`)
1299+
- Bug in :meth:`DataFrame.groupby.transform` which caused missing values when the input function can accept a :class:`pandas.DataFrame` but renames it (:issue:`23461`).
12991300

13001301
Reshaping
13011302
^^^^^^^^^

pandas/core/groupby/generic.py

+2
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,8 @@ def _choose_path(self, fast_path, slow_path, group):
583583
try:
584584
res_fast = fast_path(group)
585585

586+
if res_fast.columns != group.columns:
587+
return path, res
586588
# compare that we get the same results
587589
if res.shape == res_fast.shape:
588590
res_r = res.values.ravel()

pandas/tests/groupby/test_groupby.py

+21
Original file line numberDiff line numberDiff line change
@@ -1700,3 +1700,24 @@ def test_groupby_agg_ohlc_non_first():
17001700
result = df.groupby(pd.Grouper(freq='D')).agg(['sum', 'ohlc'])
17011701

17021702
tm.assert_frame_equal(result, expected)
1703+
1704+
1705+
def test_groupby_transform_rename():
1706+
# https://github.com/pandas-dev/pandas/issues/23461
1707+
def demean_rename(x):
1708+
result = x - x.mean()
1709+
1710+
if isinstance(x, pd.Series):
1711+
return result
1712+
1713+
result = result.rename(
1714+
columns={c: '{}_demeaned'.format(c) for c in result.columns})
1715+
1716+
return result
1717+
1718+
df = pd.DataFrame({'group': list('ababa'),
1719+
'value': [1, 1, 1, 2, 2]})
1720+
expected = pd.DataFrame({'value': [-1. / 3, -0.5, -1. / 3, 0.5, 2. / 3]})
1721+
1722+
result = df.groupby('group').transform(demean_rename)
1723+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)