Skip to content

BUG: DataFrameGroupby.transform("size") fails #45716

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 2 commits into from
Jan 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ Plotting
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
- Bug in :meth:`DataFrame.resample` ignoring ``closed="right"`` on :class:`TimedeltaIndex` (:issue:`45414`)
-
- Bug in :meth:`.DataFrameGroupBy.transform` fails when the input DataFrame has multiple columns (:issue:`27469`)

Reshaping
^^^^^^^^^
Expand Down
9 changes: 5 additions & 4 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,7 @@ def _transform_general(self, func: Callable, *args, **kwargs) -> Series:
result.name = self.obj.name
return result

def _can_use_transform_fast(self, result) -> bool:
def _can_use_transform_fast(self, func: str, result) -> bool:
return True

def filter(self, func, dropna: bool = True, *args, **kwargs):
Expand Down Expand Up @@ -1185,9 +1185,10 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs
)

def _can_use_transform_fast(self, result) -> bool:
return isinstance(result, DataFrame) and result.columns.equals(
self._obj_with_exclusions.columns
def _can_use_transform_fast(self, func: str, result) -> bool:
return func == "size" or (
isinstance(result, DataFrame)
and result.columns.equals(self._obj_with_exclusions.columns)
)

def _define_paths(self, func, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1650,7 +1650,7 @@ def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):
with com.temp_setattr(self, "observed", True):
result = getattr(self, func)(*args, **kwargs)

if self._can_use_transform_fast(result):
if self._can_use_transform_fast(func, result):
return self._wrap_transform_fast_result(result)

# only reached for DataFrameGroupBy
Expand Down
46 changes: 14 additions & 32 deletions pandas/tests/groupby/transform/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -803,39 +803,29 @@ def test_transform_with_non_scalar_group():


@pytest.mark.parametrize(
"cols,exp,comp_func",
"cols,expected",
[
("a", Series([1, 1, 1], name="a"), tm.assert_series_equal),
("a", Series([1, 1, 1], name="a")),
(
["a", "c"],
DataFrame({"a": [1, 1, 1], "c": [1, 1, 1]}),
tm.assert_frame_equal,
),
],
)
@pytest.mark.parametrize("agg_func", ["count", "rank", "size"])
def test_transform_numeric_ret(cols, exp, comp_func, agg_func, request):
if agg_func == "size" and isinstance(cols, list):
# https://github.com/pytest-dev/pytest/issues/6300
# workaround to xfail fixture/param permutations
reason = "'size' transformation not supported with NDFrameGroupy"
request.node.add_marker(pytest.mark.xfail(reason=reason))

# GH 19200
def test_transform_numeric_ret(cols, expected, agg_func):
# GH#19200 and GH#27469
df = DataFrame(
{"a": date_range("2018-01-01", periods=3), "b": range(3), "c": range(7, 10)}
)

warn = FutureWarning
if isinstance(exp, Series) or agg_func != "size":
warn = None
with tm.assert_produces_warning(warn, match="Dropping invalid columns"):
result = df.groupby("b")[cols].transform(agg_func)
result = df.groupby("b")[cols].transform(agg_func)

if agg_func == "rank":
exp = exp.astype("float")

comp_func(result, exp)
expected = expected.astype("float")
elif agg_func == "size" and cols == ["a", "c"]:
# transform("size") returns a Series
expected = expected["a"].rename(None)
tm.assert_equal(result, expected)


def test_transform_ffill():
Expand Down Expand Up @@ -1131,27 +1121,19 @@ def test_transform_agg_by_name(request, reduction_func, obj):
request.node.add_marker(
pytest.mark.xfail(reason="TODO: g.transform('ngroup') doesn't work")
)
if func == "size" and obj.ndim == 2: # GH#27469
request.node.add_marker(
pytest.mark.xfail(reason="TODO: g.transform('size') doesn't work")
)
if func == "corrwith" and isinstance(obj, Series): # GH#32293
request.node.add_marker(
pytest.mark.xfail(reason="TODO: implement SeriesGroupBy.corrwith")
)

args = {"nth": [0], "quantile": [0.5], "corrwith": [obj]}.get(func, [])

warn = None
if isinstance(obj, DataFrame) and func == "size":
warn = FutureWarning

with tm.assert_produces_warning(warn, match="Dropping invalid columns"):
result = g.transform(func, *args)
result = g.transform(func, *args)

# this is the *definition* of a transformation
tm.assert_index_equal(result.index, obj.index)
if hasattr(obj, "columns"):

if func != "size" and obj.ndim == 2:
# size returns a Series, unlike other transforms
tm.assert_index_equal(result.columns, obj.columns)

# verify that values were broadcasted across each group
Expand Down