From 52b2bd53dc622a6fcdf31a5d577c66063906b0ed Mon Sep 17 00:00:00 2001 From: jbrockmendel Date: Wed, 9 Oct 2019 12:55:35 -0700 Subject: [PATCH] CLN: dont catch on groupby.mean --- pandas/core/groupby/generic.py | 12 ++++++++++++ pandas/core/groupby/groupby.py | 13 +++---------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 41a5195008f0c..5200d33c6a1fb 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -971,6 +971,18 @@ def _cython_agg_blocks(self, how, alt=None, numeric_only=True, min_count=-1): if result is not no_result: # see if we can cast the block back to the original dtype result = maybe_downcast_numeric(result, block.dtype) + + if result.ndim == 1 and isinstance(result, np.ndarray): + # e.g. block.values was an IntegerArray + try: + # Cast back if feasible + result = type(block.values)._from_sequence( + result, dtype=block.values.dtype + ) + except ValueError: + # reshape to be valid for non-Extension Block + result = result.reshape(1, -1) + newb = block.make_block(result) new_items.append(locs) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 4e0dd65042196..a127e7dc9bada 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1212,16 +1212,9 @@ def mean(self, *args, **kwargs): Name: B, dtype: float64 """ nv.validate_groupby_func("mean", args, kwargs, ["numeric_only"]) - try: - return self._cython_agg_general( - "mean", alt=lambda x, axis: Series(x).mean(**kwargs), **kwargs - ) - except GroupByError: - raise - except Exception: - with _group_selection_context(self): - f = lambda x: x.mean(axis=self.axis, **kwargs) - return self._python_agg_general(f) + return self._cython_agg_general( + "mean", alt=lambda x, axis: Series(x).mean(**kwargs), **kwargs + ) @Substitution(name="groupby") @Appender(_common_see_also)