2
2
Routines for casting.
3
3
"""
4
4
5
- from contextlib import suppress
6
5
from datetime import date , datetime , timedelta
7
6
from typing import (
8
7
TYPE_CHECKING ,
@@ -170,20 +169,12 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
170
169
171
170
dtype = np .dtype (dtype )
172
171
173
- elif dtype .type is Period :
174
- from pandas .core .arrays import PeriodArray
175
-
176
- with suppress (TypeError ):
177
- # e.g. TypeError: int() argument must be a string, a
178
- # bytes-like object or a number, not 'Period
179
- return PeriodArray (result , freq = dtype .freq )
180
-
181
172
converted = maybe_downcast_numeric (result , dtype , do_round )
182
173
if converted is not result :
183
174
return converted
184
175
185
176
# a datetimelike
186
- # GH12821, iNaT is cast to float
177
+ # GH12821, iNaT is casted to float
187
178
if dtype .kind in ["M" , "m" ] and result .dtype .kind in ["i" , "f" ]:
188
179
if hasattr (dtype , "tz" ):
189
180
# not a numpy dtype
@@ -196,6 +187,17 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
196
187
else :
197
188
result = result .astype (dtype )
198
189
190
+ elif dtype .type is Period :
191
+ # TODO(DatetimeArray): merge with previous elif
192
+ from pandas .core .arrays import PeriodArray
193
+
194
+ try :
195
+ return PeriodArray (result , freq = dtype .freq )
196
+ except TypeError :
197
+ # e.g. TypeError: int() argument must be a string, a
198
+ # bytes-like object or a number, not 'Period
199
+ pass
200
+
199
201
return result
200
202
201
203
0 commit comments