Skip to content

Commit 776dbbb

Browse files
rhshadrachfeefladder
authored andcommitted
REG: DataFrame.agg where func returns lists and axis=1 (pandas-dev#42762)
1 parent 27930c5 commit 776dbbb

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
@@ -690,21 +690,28 @@ def agg(self):
690690
obj = self.obj
691691
axis = self.axis
692692

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

706713
if result is None:
707-
result = obj.apply(self.orig_f, axis, args=self.args, **self.kwargs)
714+
result = self.obj.apply(self.orig_f, axis, args=self.args, **self.kwargs)
708715

709716
return result
710717

pandas/tests/apply/test_frame_apply.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -644,13 +644,14 @@ def test_apply_dup_names_multi_agg():
644644
tm.assert_frame_equal(result, expected)
645645

646646

647-
def test_apply_nested_result_axis_1():
647+
@pytest.mark.parametrize("op", ["apply", "agg"])
648+
def test_apply_nested_result_axis_1(op):
648649
# GH 13820
649650
def apply_list(row):
650651
return [2 * row["A"], 2 * row["C"], 2 * row["B"]]
651652

652653
df = DataFrame(np.zeros((4, 4)), columns=list("ABCD"))
653-
result = df.apply(apply_list, axis=1)
654+
result = getattr(df, op)(apply_list, axis=1)
654655
expected = Series(
655656
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
656657
)

0 commit comments

Comments
 (0)