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 (
7
8
TYPE_CHECKING ,
@@ -133,7 +134,7 @@ def is_nested_object(obj) -> bool:
133
134
return False
134
135
135
136
136
- def maybe_downcast_to_dtype (result , dtype : Dtype ):
137
+ def maybe_downcast_to_dtype (result , dtype : Union [ str , np . dtype ] ):
137
138
"""
138
139
try to cast to the specified dtype (e.g. convert back to bool/int
139
140
or could be an astype of float64->float32
@@ -169,12 +170,20 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
169
170
170
171
dtype = np .dtype (dtype )
171
172
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
+
172
181
converted = maybe_downcast_numeric (result , dtype , do_round )
173
182
if converted is not result :
174
183
return converted
175
184
176
185
# a datetimelike
177
- # GH12821, iNaT is casted to float
186
+ # GH12821, iNaT is cast to float
178
187
if dtype .kind in ["M" , "m" ] and result .dtype .kind in ["i" , "f" ]:
179
188
if hasattr (dtype , "tz" ):
180
189
# not a numpy dtype
@@ -187,17 +196,6 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
187
196
else :
188
197
result = result .astype (dtype )
189
198
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
-
201
199
return result
202
200
203
201
0 commit comments