@@ -649,10 +649,12 @@ def astype_nansafe(arr, dtype, copy=True):
649
649
if issubclass (dtype .type , text_type ):
650
650
# in Py3 that's str, in Py2 that's unicode
651
651
return lib .astype_unicode (arr .ravel ()).reshape (arr .shape )
652
+
652
653
elif issubclass (dtype .type , string_types ):
653
654
return lib .astype_str (arr .ravel ()).reshape (arr .shape )
655
+
654
656
elif is_datetime64_dtype (arr ):
655
- if dtype == object :
657
+ if is_object_dtype ( dtype ) :
656
658
return tslib .ints_to_pydatetime (arr .view (np .int64 ))
657
659
elif dtype == np .int64 :
658
660
return arr .view (dtype )
@@ -666,10 +668,10 @@ def astype_nansafe(arr, dtype, copy=True):
666
668
to_dtype = dtype ))
667
669
668
670
elif is_timedelta64_dtype (arr ):
669
- if dtype == np .int64 :
670
- return arr .view (dtype )
671
- elif dtype == object :
671
+ if is_object_dtype (dtype ):
672
672
return tslib .ints_to_pytimedelta (arr .view (np .int64 ))
673
+ elif dtype == np .int64 :
674
+ return arr .view (dtype )
673
675
674
676
# in py3, timedelta64[ns] are int64
675
677
if ((PY3 and dtype not in [_INT64_DTYPE , _TD_DTYPE ]) or
@@ -696,9 +698,21 @@ def astype_nansafe(arr, dtype, copy=True):
696
698
raise ValueError ('Cannot convert non-finite values (NA or inf) to '
697
699
'integer' )
698
700
699
- elif is_object_dtype (arr .dtype ) and np .issubdtype (dtype .type , np .integer ):
701
+ elif is_object_dtype (arr ):
702
+
700
703
# work around NumPy brokenness, #1987
701
- return lib .astype_intsafe (arr .ravel (), dtype ).reshape (arr .shape )
704
+ if np .issubdtype (dtype .type , np .integer ):
705
+ return lib .astype_intsafe (arr .ravel (), dtype ).reshape (arr .shape )
706
+
707
+ # if we have a datetime/timedelta array of objects
708
+ # then coerce to a proper dtype and recall astype_nansafe
709
+
710
+ elif is_datetime64_dtype (dtype ):
711
+ from pandas import to_datetime
712
+ return astype_nansafe (to_datetime (arr ).values , dtype , copy = copy )
713
+ elif is_timedelta64_dtype (dtype ):
714
+ from pandas import to_timedelta
715
+ return astype_nansafe (to_timedelta (arr ).values , dtype , copy = copy )
702
716
703
717
if dtype .name in ("datetime64" , "timedelta64" ):
704
718
msg = ("Passing in '{dtype}' dtype with no frequency is "
@@ -709,7 +723,6 @@ def astype_nansafe(arr, dtype, copy=True):
709
723
dtype = np .dtype (dtype .name + "[ns]" )
710
724
711
725
if copy :
712
-
713
726
return arr .astype (dtype , copy = True )
714
727
return arr .view (dtype )
715
728
0 commit comments