Skip to content

BUG: DataFrameGroupBy.transform with axis=1 fails (#36308) #36350

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 6 commits into from
Nov 14, 2020
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.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ Groupby/resample/rolling
- Bug in :meth:`Rolling.median` and :meth:`Rolling.quantile` returned wrong values for :class:`BaseIndexer` subclasses with non-monotonic starting or ending points for windows (:issue:`37153`)
- Bug in :meth:`DataFrame.groupby` dropped ``nan`` groups from result with ``dropna=False`` when grouping over a single column (:issue:`35646`, :issue:`35542`)
- Bug in :meth:`DataFrameGroupBy.head`, :meth:`DataFrameGroupBy.tail`, :meth:`SeriesGroupBy.head`, and :meth:`SeriesGroupBy.tail` would raise when used with ``axis=1`` (:issue:`9772`)

- Bug in :meth:`DataFrameGroupBy.transform` would raise when used with ``axis=1`` and a transformation kernel (e.g. "shift") (:issue:`36308`)

Reshaping
^^^^^^^^^
Expand Down
13 changes: 9 additions & 4 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1675,11 +1675,16 @@ def _wrap_transformed_output(
DataFrame
"""
indexed_output = {key.position: val for key, val in output.items()}
columns = Index(key.label for key in output)
columns.name = self.obj.columns.name

result = self.obj._constructor(indexed_output)
result.columns = columns

if self.axis == 1:
result = result.T
result.columns = self.obj.columns
else:
columns = Index(key.label for key in output)
columns.name = self.obj.columns.name
result.columns = columns

result.index = self.obj.index

return result
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2365,7 +2365,7 @@ def cumcount(self, ascending: bool = True):
dtype: int64
"""
with group_selection_context(self):
index = self._selected_obj.index
index = self._selected_obj._get_axis(self.axis)
cumcounts = self._cumcount_array(ascending=ascending)
return self._obj_1d_constructor(cumcounts, index)

Expand Down Expand Up @@ -2706,8 +2706,8 @@ def pct_change(self, periods=1, fill_method="pad", limit=None, freq=None, axis=0
fill_method = "pad"
limit = 0
filled = getattr(self, fill_method)(limit=limit)
fill_grp = filled.groupby(self.grouper.codes)
shifted = fill_grp.shift(periods=periods, freq=freq)
fill_grp = filled.groupby(self.grouper.codes, axis=self.axis)
shifted = fill_grp.shift(periods=periods, freq=freq, axis=self.axis)
return (filled / shifted) - 1

@Substitution(name="groupby")
Expand Down
2 changes: 0 additions & 2 deletions pandas/tests/frame/apply/test_frame_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ def test_transform_groupby_kernel(axis, float_frame, op):
pytest.xfail("DataFrame.cumcount does not exist")
if op == "tshift":
pytest.xfail("Only works on time index and is deprecated")
if axis == 1 or axis == "columns":
pytest.xfail("GH 36308: groupby.transform with axis=1 is broken")

args = [0.0] if op == "fillna" else []
if axis == 0 or axis == "index":
Expand Down
20 changes: 19 additions & 1 deletion pandas/tests/groupby/transform/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,25 @@ def test_transform_broadcast(tsframe, ts):
assert_fp_equal(res.xs(idx), agged[idx])


def test_transform_axis(tsframe):
def test_transform_axis_1(transformation_func):
# GH 36308
if transformation_func == "tshift":
pytest.xfail("tshift is deprecated")
args = ("ffill",) if transformation_func == "fillna" else tuple()

df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"])
result = df.groupby([0, 0, 1], axis=1).transform(transformation_func, *args)
expected = df.T.groupby([0, 0, 1]).transform(transformation_func, *args).T

if transformation_func == "diff":
# Result contains nans, so transpose coerces to float
expected["b"] = expected["b"].astype("int64")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh i c you are doing this because we want to compare to ints, got it ,then this is fine.


# cumcount returns Series; the rest are DataFrame
tm.assert_equal(result, expected)


def test_transform_axis_ts(tsframe):

# make sure that we are setting the axes
# correctly when on axis=0 or 1
Expand Down