Skip to content

Commit

Permalink
REF: Move the rest of DataFrame.agg into apply (pandas-dev#39955)
Browse files Browse the repository at this point in the history
  • Loading branch information
rhshadrach authored Feb 21, 2021
1 parent fad5fee commit 1b6b581
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 30 deletions.
30 changes: 30 additions & 0 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ def f(x):
else:
f = func

self.orig_f: AggFuncType = func
self.f: AggFuncType = f

@property
Expand Down Expand Up @@ -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
Expand Down
34 changes: 4 additions & 30 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand Down

0 comments on commit 1b6b581

Please sign in to comment.