Skip to content

Commit a429057

Browse files
Backport PR #42762: REG: DataFrame.agg where func returns lists and axis=1 (#42786)
Co-authored-by: Richard Shadrach <[email protected]>
1 parent 5cc7d05 commit a429057

File tree

3 files changed

+22
-13
lines changed

3 files changed

+22
-13
lines changed

doc/source/whatsnew/v1.3.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Fixed regressions
1818
- Regression in updating values of :class:`pandas.Series` using boolean index, created by using :meth:`pandas.DataFrame.pop` (:issue:`42530`)
1919
- Regression in :meth:`DataFrame.from_records` with empty records (:issue:`42456`)
2020
- Fixed regression in :meth:`DataFrame.shift` where TypeError occurred when shifting DataFrame created by concatenation of slices and fills with values (:issue:`42719`)
21+
- Regression in :meth:`DataFrame.agg` when the ``func`` argument returned lists and ``axis=1`` (:issue:`42727`)
2122
-
2223

2324
.. ---------------------------------------------------------------------------

pandas/core/apply.py

+18-11
Original file line numberDiff line numberDiff line change
@@ -691,21 +691,28 @@ def agg(self):
691691
obj = self.obj
692692
axis = self.axis
693693

694+
# TODO: Avoid having to change state
695+
self.obj = self.obj if self.axis == 0 else self.obj.T
696+
self.axis = 0
697+
698+
result = None
699+
try:
700+
result = super().agg()
701+
except TypeError as err:
702+
exc = TypeError(
703+
"DataFrame constructor called with "
704+
f"incompatible data and dtype: {err}"
705+
)
706+
raise exc from err
707+
finally:
708+
self.obj = obj
709+
self.axis = axis
710+
694711
if axis == 1:
695-
result = FrameRowApply(
696-
obj.T,
697-
self.orig_f,
698-
self.raw,
699-
self.result_type,
700-
self.args,
701-
self.kwargs,
702-
).agg()
703712
result = result.T if result is not None else result
704-
else:
705-
result = super().agg()
706713

707714
if result is None:
708-
result = obj.apply(self.orig_f, axis, args=self.args, **self.kwargs)
715+
result = self.obj.apply(self.orig_f, axis, args=self.args, **self.kwargs)
709716

710717
return result
711718

pandas/tests/apply/test_frame_apply.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -671,13 +671,14 @@ def test_apply_dup_names_multi_agg():
671671
tm.assert_frame_equal(result, expected)
672672

673673

674-
def test_apply_nested_result_axis_1():
674+
@pytest.mark.parametrize("op", ["apply", "agg"])
675+
def test_apply_nested_result_axis_1(op):
675676
# GH 13820
676677
def apply_list(row):
677678
return [2 * row["A"], 2 * row["C"], 2 * row["B"]]
678679

679680
df = DataFrame(np.zeros((4, 4)), columns=list("ABCD"))
680-
result = df.apply(apply_list, axis=1)
681+
result = getattr(df, op)(apply_list, axis=1)
681682
expected = Series(
682683
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
683684
)

0 commit comments

Comments
 (0)