22Routines for casting.
33"""
44
5+ from contextlib import suppress
56from datetime import date , datetime , timedelta
67from typing import TYPE_CHECKING , Any , List , Optional , Tuple , Type
78
@@ -156,12 +157,20 @@ def maybe_downcast_to_dtype(result, dtype):
156157
157158 dtype = np .dtype (dtype )
158159
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+
159168 converted = maybe_downcast_numeric (result , dtype , do_round )
160169 if converted is not result :
161170 return converted
162171
163172 # a datetimelike
164- # GH12821, iNaT is casted to float
173+ # GH12821, iNaT is cast to float
165174 if dtype .kind in ["M" , "m" ] and result .dtype .kind in ["i" , "f" ]:
166175 if hasattr (dtype , "tz" ):
167176 # not a numpy dtype
@@ -174,17 +183,6 @@ def maybe_downcast_to_dtype(result, dtype):
174183 else :
175184 result = result .astype (dtype )
176185
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-
188186 return result
189187
190188
0 commit comments