From 7fe59506c901f09981344a54dc819330a4a17bb9 Mon Sep 17 00:00:00 2001 From: Richard Shadrach Date: Sun, 21 Feb 2021 07:32:59 -0500 Subject: [PATCH] CLN: Move the rest of Series.apply into apply --- pandas/core/apply.py | 30 ++++++++++++++++++++++++++++++ pandas/core/series.py | 23 +---------------------- 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/pandas/core/apply.py b/pandas/core/apply.py index b41c432dff172..b0f8534f2da54 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -845,6 +845,36 @@ def apply(self) -> FrameOrSeriesUnion: return self.apply_standard() + def agg(self): + result = super().agg() + if result is None: + f = self.f + args = self.args + kwargs = self.kwargs + + # string, list-like, and dict-like are entirely handled in super + assert callable(f) + + # we can be called from an inner function which + # passes this meta-data + kwargs.pop("_axis", None) + kwargs.pop("_level", None) + + # try a regular apply, this evaluates lambdas + # row-by-row; however if the lambda is expected a Series + # expression, e.g.: lambda x: x-x.quantile(0.25) + # this will fail, so we can try a vectorized evaluation + + # we cannot FIRST try the vectorized evaluation, because + # then .agg and .apply would have different semantics if the + # operation is actually defined on the Series, e.g. str + try: + result = self.obj.apply(f, *args, **kwargs) + except (ValueError, AttributeError, TypeError): + result = f(self.obj, *args, **kwargs) + + return result + def apply_empty_result(self) -> Series: obj = self.obj return obj._constructor(dtype=obj.dtype, index=obj.index).__finalize__( diff --git a/pandas/core/series.py b/pandas/core/series.py index cbb66918a661b..f3fbecd748e6d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4003,26 +4003,6 @@ def aggregate(self, func=None, axis=0, *args, **kwargs): op = series_apply(self, func, args=args, kwargs=kwargs) result = op.agg() - if result is None: - - # we can be called from an inner function which - # passes this meta-data - kwargs.pop("_axis", None) - kwargs.pop("_level", None) - - # try a regular apply, this evaluates lambdas - # row-by-row; however if the lambda is expected a Series - # expression, e.g.: lambda x: x-x.quantile(0.25) - # this will fail, so we can try a vectorized evaluation - - # we cannot FIRST try the vectorized evaluation, because - # then .agg and .apply would have different semantics if the - # operation is actually defined on the Series, e.g. str - try: - result = self.apply(func, *args, **kwargs) - except (ValueError, AttributeError, TypeError): - result = func(self, *args, **kwargs) - return result agg = aggregate @@ -4146,8 +4126,7 @@ def apply( Helsinki 2.484907 dtype: float64 """ - op = series_apply(self, func, convert_dtype, args, kwargs) - return op.apply() + return series_apply(self, func, convert_dtype, args, kwargs).apply() def _reduce( self,