Skip to content

BUG: groupby transform fillna produces wrong result #31101

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
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,7 @@ Plotting
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^

-
-

- Bug in :meth:`DataFrameGroupby.transform` produces incorrect result with ``func='fillna'`` (:issue:`30918`)

Reshaping
^^^^^^^^^
Expand Down
21 changes: 10 additions & 11 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1418,17 +1418,16 @@ def transform(self, func, *args, **kwargs):
# and deal with possible broadcasting below.
result = getattr(self, func)(*args, **kwargs)

# a reduction transform
if not isinstance(result, DataFrame):
return self._transform_general(func, *args, **kwargs)

obj = self._obj_with_exclusions

# nuisance columns
if not result.columns.equals(obj.columns):
return self._transform_general(func, *args, **kwargs)

return self._transform_fast(result, func)
if (
isinstance(result, DataFrame)
and result.columns.equals(self._obj_with_exclusions.columns)
and result.index.equals(self.grouper.result_index)
):
# GH 30918
# Call _transform_fast only when we know func is an aggregation
return self._transform_fast(result, func)

return self._transform_general(func, *args, **kwargs)

def _transform_fast(self, result: DataFrame, func_nm: str) -> DataFrame:
"""
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/groupby/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,19 @@ def test_dispatch_transform(tsframe):
tm.assert_frame_equal(filled, expected)


def test_transform_fillna():
# GH 30918
df = pd.DataFrame(
{
"A": ["foo", "foo", "foo", "foo", "bar", "bar", "baz"],
"B": [1, 2, np.nan, 3, 3, np.nan, 4],
}
)
result = df.groupby("A").transform("fillna", value=9)
expected = df[["B"]].fillna(value=9)
tm.assert_frame_equal(result, expected)


def test_transform_select_columns(df):
f = lambda x: x.mean()
result = df.groupby("A")[["C", "D"]].transform(f)
Expand Down