Skip to content

Commit

Permalink
REG: DataFrame.agg where func returns lists and axis=1 (pandas-dev#42762
Browse files Browse the repository at this point in the history
)
  • Loading branch information
rhshadrach authored Jul 28, 2021
1 parent 8924277 commit 8e07787
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 13 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Fixed regressions
- Regression in updating values of :class:`pandas.Series` using boolean index, created by using :meth:`pandas.DataFrame.pop` (:issue:`42530`)
- Regression in :meth:`DataFrame.from_records` with empty records (:issue:`42456`)
- Fixed regression in :meth:`DataFrame.shift` where TypeError occurred when shifting DataFrame created by concatenation of slices and fills with values (:issue:`42719`)
- Regression in :meth:`DataFrame.agg` when the ``func`` argument returned lists and ``axis=1`` (:issue:`42727`)
-

.. ---------------------------------------------------------------------------
Expand Down
29 changes: 18 additions & 11 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,21 +690,28 @@ def agg(self):
obj = self.obj
axis = self.axis

# TODO: Avoid having to change state
self.obj = self.obj if self.axis == 0 else self.obj.T
self.axis = 0

result = None
try:
result = super().agg()
except TypeError as err:
exc = TypeError(
"DataFrame constructor called with "
f"incompatible data and dtype: {err}"
)
raise exc from err
finally:
self.obj = obj
self.axis = axis

if axis == 1:
result = FrameRowApply(
obj.T,
self.orig_f,
self.raw,
self.result_type,
self.args,
self.kwargs,
).agg()
result = result.T if result is not None else result
else:
result = super().agg()

if result is None:
result = obj.apply(self.orig_f, axis, args=self.args, **self.kwargs)
result = self.obj.apply(self.orig_f, axis, args=self.args, **self.kwargs)

return result

Expand Down
5 changes: 3 additions & 2 deletions pandas/tests/apply/test_frame_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,13 +644,14 @@ def test_apply_dup_names_multi_agg():
tm.assert_frame_equal(result, expected)


def test_apply_nested_result_axis_1():
@pytest.mark.parametrize("op", ["apply", "agg"])
def test_apply_nested_result_axis_1(op):
# GH 13820
def apply_list(row):
return [2 * row["A"], 2 * row["C"], 2 * row["B"]]

df = DataFrame(np.zeros((4, 4)), columns=list("ABCD"))
result = df.apply(apply_list, axis=1)
result = getattr(df, op)(apply_list, axis=1)
expected = Series(
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
)
Expand Down

0 comments on commit 8e07787

Please sign in to comment.