diff --git a/pandas/core/apply.py b/pandas/core/apply.py index b0f8534f2da54..62258059b410e 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -151,6 +151,7 @@ def f(x): else: f = func + self.orig_f: AggFuncType = func self.f: AggFuncType = f @property @@ -527,6 +528,35 @@ def apply(self) -> FrameOrSeriesUnion: return self.apply_standard() + 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 = result.T if result is not None else result + + if result is None: + result = self.obj.apply(self.orig_f, axis, args=self.args, **self.kwargs) + + return result + def apply_empty_result(self): """ we have an empty result; at least 1 axis is 0 diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8e7dd76b0547c..7a216e411dcc2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7728,21 +7728,14 @@ def _gotitem( examples=_agg_examples_doc, ) def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): + from pandas.core.apply import frame_apply + axis = self._get_axis_number(axis) relabeling, func, columns, order = reconstruct_func(func, **kwargs) - result = None - try: - result = self._aggregate(func, axis, *args, **kwargs) - except TypeError as err: - exc = TypeError( - "DataFrame constructor called with " - f"incompatible data and dtype: {err}" - ) - raise exc from err - if result is None: - return self.apply(func, axis=axis, args=args, **kwargs) + op = frame_apply(self, func=func, axis=axis, args=args, kwargs=kwargs) + result = op.agg() if relabeling: # This is to keep the order to columns occurrence unchanged, and also @@ -7758,25 +7751,6 @@ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): return result - def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs): - from pandas.core.apply import frame_apply - - op = frame_apply( - self if axis == 0 else self.T, - func=arg, - axis=0, - args=args, - kwargs=kwargs, - ) - result = op.agg() - - if axis == 1: - # NDFrame.aggregate returns a tuple, and we need to transpose - # only result - result = result.T if result is not None else result - - return result - agg = aggregate @doc(