@@ -767,19 +767,23 @@ def _index_with_as_index(self, b):
767
767
new .names = gp .names + original .names
768
768
return new
769
769
770
- def _try_cast (self , result , obj ):
770
+ def _try_cast (self , result , obj , numeric_only = False ):
771
771
"""
772
772
try to cast the result to our obj original type,
773
773
we may have roundtripped thru object in the mean-time
774
774
775
+ if numeric_only is True, then only try to cast numerics
776
+ and not datetimelikes
777
+
775
778
"""
776
779
if obj .ndim > 1 :
777
780
dtype = obj .values .dtype
778
781
else :
779
782
dtype = obj .dtype
780
783
781
784
if not is_scalar (result ):
782
- result = _possibly_downcast_to_dtype (result , dtype )
785
+ if numeric_only and is_numeric_dtype (dtype ) or not numeric_only :
786
+ result = _possibly_downcast_to_dtype (result , dtype )
783
787
784
788
return result
785
789
@@ -830,7 +834,7 @@ def _python_agg_general(self, func, *args, **kwargs):
830
834
for name , obj in self ._iterate_slices ():
831
835
try :
832
836
result , counts = self .grouper .agg_series (obj , f )
833
- output [name ] = self ._try_cast (result , obj )
837
+ output [name ] = self ._try_cast (result , obj , numeric_only = True )
834
838
except TypeError :
835
839
continue
836
840
@@ -1117,7 +1121,9 @@ def sem(self, ddof=1):
1117
1121
@Appender (_doc_template )
1118
1122
def size (self ):
1119
1123
"""Compute group sizes"""
1120
- return self .grouper .size ()
1124
+ result = self .grouper .size ()
1125
+ result .name = getattr (self , 'name' , None )
1126
+ return result
1121
1127
1122
1128
sum = _groupby_function ('sum' , 'add' , np .sum )
1123
1129
prod = _groupby_function ('prod' , 'prod' , np .prod )
@@ -1689,7 +1695,9 @@ def size(self):
1689
1695
ids , _ , ngroup = self .group_info
1690
1696
ids = _ensure_platform_int (ids )
1691
1697
out = np .bincount (ids [ids != - 1 ], minlength = ngroup or None )
1692
- return Series (out , index = self .result_index , dtype = 'int64' )
1698
+ return Series (out ,
1699
+ index = self .result_index ,
1700
+ dtype = 'int64' )
1693
1701
1694
1702
@cache_readonly
1695
1703
def _max_groupsize (self ):
@@ -2908,7 +2916,8 @@ def transform(self, func, *args, **kwargs):
2908
2916
result = concat (results ).sort_index ()
2909
2917
2910
2918
# we will only try to coerce the result type if
2911
- # we have a numeric dtype
2919
+ # we have a numeric dtype, as these are *always* udfs
2920
+ # the cython take a different path (and casting)
2912
2921
dtype = self ._selected_obj .dtype
2913
2922
if is_numeric_dtype (dtype ):
2914
2923
result = _possibly_downcast_to_dtype (result , dtype )
0 commit comments