@@ -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,11 @@ 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
+
1126
+ if isinstance (self .obj , Series ):
1127
+ result .name = getattr (self , 'name' , None )
1128
+ return result
1121
1129
1122
1130
sum = _groupby_function ('sum' , 'add' , np .sum )
1123
1131
prod = _groupby_function ('prod' , 'prod' , np .prod )
@@ -1689,7 +1697,9 @@ def size(self):
1689
1697
ids , _ , ngroup = self .group_info
1690
1698
ids = _ensure_platform_int (ids )
1691
1699
out = np .bincount (ids [ids != - 1 ], minlength = ngroup or None )
1692
- return Series (out , index = self .result_index , dtype = 'int64' )
1700
+ return Series (out ,
1701
+ index = self .result_index ,
1702
+ dtype = 'int64' )
1693
1703
1694
1704
@cache_readonly
1695
1705
def _max_groupsize (self ):
@@ -2908,7 +2918,8 @@ def transform(self, func, *args, **kwargs):
2908
2918
result = concat (results ).sort_index ()
2909
2919
2910
2920
# we will only try to coerce the result type if
2911
- # we have a numeric dtype
2921
+ # we have a numeric dtype, as these are *always* udfs
2922
+ # the cython take a different path (and casting)
2912
2923
dtype = self ._selected_obj .dtype
2913
2924
if is_numeric_dtype (dtype ):
2914
2925
result = _possibly_downcast_to_dtype (result , dtype )
0 commit comments