2
2
Routines for casting.
3
3
"""
4
4
5
+ from contextlib import suppress
5
6
from datetime import date , datetime , timedelta
6
7
from typing import TYPE_CHECKING , Any , List , Optional , Tuple , Type
7
8
@@ -156,12 +157,20 @@ def maybe_downcast_to_dtype(result, dtype):
156
157
157
158
dtype = np .dtype (dtype )
158
159
160
+ elif dtype .type is Period :
161
+ from pandas .core .arrays import PeriodArray
162
+
163
+ with suppress (TypeError ):
164
+ # e.g. TypeError: int() argument must be a string, a
165
+ # bytes-like object or a number, not 'Period
166
+ return PeriodArray (result , freq = dtype .freq )
167
+
159
168
converted = maybe_downcast_numeric (result , dtype , do_round )
160
169
if converted is not result :
161
170
return converted
162
171
163
172
# a datetimelike
164
- # GH12821, iNaT is casted to float
173
+ # GH12821, iNaT is cast to float
165
174
if dtype .kind in ["M" , "m" ] and result .dtype .kind in ["i" , "f" ]:
166
175
if hasattr (dtype , "tz" ):
167
176
# not a numpy dtype
@@ -174,17 +183,6 @@ def maybe_downcast_to_dtype(result, dtype):
174
183
else :
175
184
result = result .astype (dtype )
176
185
177
- elif dtype .type is Period :
178
- # TODO(DatetimeArray): merge with previous elif
179
- from pandas .core .arrays import PeriodArray
180
-
181
- try :
182
- return PeriodArray (result , freq = dtype .freq )
183
- except TypeError :
184
- # e.g. TypeError: int() argument must be a string, a
185
- # bytes-like object or a number, not 'Period
186
- pass
187
-
188
186
return result
189
187
190
188
0 commit comments