53
53
is_datetime64_dtype ,
54
54
is_datetime64_ns_dtype ,
55
55
is_datetime64tz_dtype ,
56
- is_datetime_or_timedelta_dtype ,
57
56
is_dtype_equal ,
58
57
is_extension_array_dtype ,
59
58
is_float ,
@@ -219,14 +218,11 @@ def maybe_downcast_to_dtype(result, dtype: Union[str, np.dtype]):
219
218
# a datetimelike
220
219
# GH12821, iNaT is cast to float
221
220
if dtype .kind in ["M" , "m" ] and result .dtype .kind in ["i" , "f" ]:
222
- if hasattr (dtype , "tz" ):
223
- # not a numpy dtype
224
- if dtype .tz :
225
- # convert to datetime and change timezone
226
- from pandas import to_datetime
227
-
228
- result = to_datetime (result ).tz_localize ("utc" )
229
- result = result .tz_convert (dtype .tz )
221
+ if isinstance (dtype , DatetimeTZDtype ):
222
+ # convert to datetime and change timezone
223
+ i8values = result .astype ("i8" , copy = False )
224
+ cls = dtype .construct_array_type ()
225
+ result = cls ._simple_new (i8values , dtype = dtype )
230
226
else :
231
227
result = result .astype (dtype )
232
228
@@ -609,13 +605,12 @@ def maybe_promote(dtype, fill_value=np.nan):
609
605
dtype = mst
610
606
611
607
elif fill_value is None or fill_value is libmissing .NA :
608
+ # Note: we already excluded dt64/td64 dtypes above
612
609
if is_float_dtype (dtype ) or is_complex_dtype (dtype ):
613
610
fill_value = np .nan
614
611
elif is_integer_dtype (dtype ):
615
612
dtype = np .float64
616
613
fill_value = np .nan
617
- elif is_datetime_or_timedelta_dtype (dtype ):
618
- fill_value = dtype .type ("NaT" , "ns" )
619
614
else :
620
615
dtype = np .dtype (np .object_ )
621
616
if fill_value is not libmissing .NA :
@@ -951,7 +946,7 @@ def astype_td64_unit_conversion(
951
946
952
947
953
948
def astype_nansafe (
954
- arr , dtype : DtypeObj , copy : bool = True , skipna : bool = False
949
+ arr : np . ndarray , dtype : DtypeObj , copy : bool = True , skipna : bool = False
955
950
) -> ArrayLike :
956
951
"""
957
952
Cast the elements of an array to a given dtype a nan-safe manner.
@@ -979,6 +974,9 @@ def astype_nansafe(
979
974
order = "F" if flags .f_contiguous else "C"
980
975
return result .reshape (arr .shape , order = order )
981
976
977
+ # We get here with 0-dim from sparse
978
+ arr = np .atleast_1d (arr )
979
+
982
980
# dispatch on extension dtype if needed
983
981
if isinstance (dtype , ExtensionDtype ):
984
982
return dtype .construct_array_type ()._from_sequence (arr , dtype = dtype , copy = copy )
@@ -995,9 +993,7 @@ def astype_nansafe(
995
993
return arr .astype (dtype , copy = copy )
996
994
997
995
if issubclass (dtype .type , str ):
998
- return lib .ensure_string_array (
999
- arr .ravel (), skipna = skipna , convert_na_value = False
1000
- ).reshape (arr .shape )
996
+ return lib .ensure_string_array (arr , skipna = skipna , convert_na_value = False )
1001
997
1002
998
elif is_datetime64_dtype (arr ):
1003
999
if dtype == np .int64 :
@@ -1031,7 +1027,7 @@ def astype_nansafe(
1031
1027
1032
1028
# work around NumPy brokenness, #1987
1033
1029
if np .issubdtype (dtype .type , np .integer ):
1034
- return lib .astype_intsafe (arr . ravel () , dtype ). reshape ( arr . shape )
1030
+ return lib .astype_intsafe (arr , dtype )
1035
1031
1036
1032
# if we have a datetime/timedelta array of objects
1037
1033
# then coerce to a proper dtype and recall astype_nansafe
@@ -1092,27 +1088,22 @@ def soft_convert_objects(
1092
1088
raise ValueError ("At least one of datetime, numeric or timedelta must be True." )
1093
1089
1094
1090
# Soft conversions
1095
- if datetime :
1091
+ if datetime or timedelta :
1096
1092
# GH 20380, when datetime is beyond year 2262, hence outside
1097
1093
# bound of nanosecond-resolution 64-bit integers.
1098
1094
try :
1099
- values = lib .maybe_convert_objects (values , convert_datetime = True )
1095
+ values = lib .maybe_convert_objects (
1096
+ values , convert_datetime = datetime , convert_timedelta = timedelta
1097
+ )
1100
1098
except OutOfBoundsDatetime :
1101
- pass
1102
-
1103
- if timedelta and is_object_dtype (values .dtype ):
1104
- # Object check to ensure only run if previous did not convert
1105
- values = lib .maybe_convert_objects (values , convert_timedelta = True )
1099
+ return values
1106
1100
1107
1101
if numeric and is_object_dtype (values .dtype ):
1108
- try :
1109
- converted = lib .maybe_convert_numeric (values , set (), coerce_numeric = True )
1110
- except (ValueError , TypeError ):
1111
- pass
1112
- else :
1113
- # If all NaNs, then do not-alter
1114
- values = converted if not isna (converted ).all () else values
1115
- values = values .copy () if copy else values
1102
+ converted = lib .maybe_convert_numeric (values , set (), coerce_numeric = True )
1103
+
1104
+ # If all NaNs, then do not-alter
1105
+ values = converted if not isna (converted ).all () else values
1106
+ values = values .copy () if copy else values
1116
1107
1117
1108
return values
1118
1109
@@ -1274,6 +1265,7 @@ def try_datetime(v):
1274
1265
# safe coerce to datetime64
1275
1266
try :
1276
1267
# GH19671
1268
+ # tznaive only
1277
1269
v = tslib .array_to_datetime (v , require_iso8601 = True , errors = "raise" )[0 ]
1278
1270
except ValueError :
1279
1271
@@ -1285,11 +1277,12 @@ def try_datetime(v):
1285
1277
try :
1286
1278
1287
1279
values , tz = conversion .datetime_to_datetime64 (v )
1288
- return DatetimeIndex (values ).tz_localize ("UTC" ).tz_convert (tz = tz )
1289
1280
except (ValueError , TypeError ):
1290
1281
pass
1291
-
1292
- except Exception :
1282
+ else :
1283
+ return DatetimeIndex (values ).tz_localize ("UTC" ).tz_convert (tz = tz )
1284
+ except TypeError :
1285
+ # e.g. <class 'numpy.timedelta64'> is not convertible to datetime
1293
1286
pass
1294
1287
1295
1288
return v .reshape (shape )
0 commit comments