@@ -50,7 +50,7 @@ class providing the base-class of operations.
50
50
from pandas .errors import AbstractMethodError
51
51
from pandas .util ._decorators import Appender , Substitution , cache_readonly , doc
52
52
53
- from pandas .core .dtypes .cast import maybe_cast_result
53
+ from pandas .core .dtypes .cast import maybe_cast_result , maybe_downcast_to_dtype
54
54
from pandas .core .dtypes .common import (
55
55
ensure_float ,
56
56
is_bool_dtype ,
@@ -1185,22 +1185,24 @@ def _python_agg_general(self, func, *args, **kwargs):
1185
1185
1186
1186
assert result is not None
1187
1187
key = base .OutputKey (label = name , position = idx )
1188
- output [key ] = maybe_cast_result (result , obj , numeric_only = True )
1189
1188
1190
- if not output :
1191
- return self . _python_apply_general ( f , self . _selected_obj )
1189
+ if is_numeric_dtype ( obj . dtype ) :
1190
+ result = maybe_downcast_to_dtype ( result , obj . dtype )
1192
1191
1193
- if self .grouper ._filter_empty_groups :
1194
-
1195
- mask = counts .ravel () > 0
1196
- for key , result in output .items ():
1192
+ if self .grouper ._filter_empty_groups :
1193
+ mask = counts .ravel () > 0
1197
1194
1198
1195
# since we are masking, make sure that we have a float object
1199
1196
values = result
1200
1197
if is_numeric_dtype (values .dtype ):
1201
1198
values = ensure_float (values )
1202
1199
1203
- output [key ] = maybe_cast_result (values [mask ], result )
1200
+ result = maybe_downcast_to_dtype (values [mask ], result .dtype )
1201
+
1202
+ output [key ] = result
1203
+
1204
+ if not output :
1205
+ return self ._python_apply_general (f , self ._selected_obj )
1204
1206
1205
1207
return self ._wrap_aggregated_output (output , index = self .grouper .result_index )
1206
1208
0 commit comments