Skip to content

Commit 548f83d

Browse files
jbrockmendelWillAyd
authored andcommitted
CLN: dont catch on groupby.mean (#28878)
1 parent 71f8ab9 commit 548f83d

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

pandas/core/groupby/generic.py

+12
Original file line numberDiff line numberDiff line change
@@ -971,6 +971,18 @@ def _cython_agg_blocks(self, how, alt=None, numeric_only=True, min_count=-1):
971971
if result is not no_result:
972972
# see if we can cast the block back to the original dtype
973973
result = maybe_downcast_numeric(result, block.dtype)
974+
975+
if result.ndim == 1 and isinstance(result, np.ndarray):
976+
# e.g. block.values was an IntegerArray
977+
try:
978+
# Cast back if feasible
979+
result = type(block.values)._from_sequence(
980+
result, dtype=block.values.dtype
981+
)
982+
except ValueError:
983+
# reshape to be valid for non-Extension Block
984+
result = result.reshape(1, -1)
985+
974986
newb = block.make_block(result)
975987

976988
new_items.append(locs)

pandas/core/groupby/groupby.py

+3-10
Original file line numberDiff line numberDiff line change
@@ -1217,16 +1217,9 @@ def mean(self, *args, **kwargs):
12171217
Name: B, dtype: float64
12181218
"""
12191219
nv.validate_groupby_func("mean", args, kwargs, ["numeric_only"])
1220-
try:
1221-
return self._cython_agg_general(
1222-
"mean", alt=lambda x, axis: Series(x).mean(**kwargs), **kwargs
1223-
)
1224-
except GroupByError:
1225-
raise
1226-
except Exception:
1227-
with _group_selection_context(self):
1228-
f = lambda x: x.mean(axis=self.axis, **kwargs)
1229-
return self._python_agg_general(f)
1220+
return self._cython_agg_general(
1221+
"mean", alt=lambda x, axis: Series(x).mean(**kwargs), **kwargs
1222+
)
12301223

12311224
@Substitution(name="groupby")
12321225
@Appender(_common_see_also)

0 commit comments

Comments
 (0)