22Routines for casting.
33"""
44
5- from contextlib import suppress
65from datetime import date , datetime , timedelta
76from typing import (
87 TYPE_CHECKING ,
@@ -170,20 +169,12 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
170169
171170 dtype = np .dtype (dtype )
172171
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-
181172 converted = maybe_downcast_numeric (result , dtype , do_round )
182173 if converted is not result :
183174 return converted
184175
185176 # a datetimelike
186- # GH12821, iNaT is cast to float
177+ # GH12821, iNaT is casted to float
187178 if dtype .kind in ["M" , "m" ] and result .dtype .kind in ["i" , "f" ]:
188179 if hasattr (dtype , "tz" ):
189180 # not a numpy dtype
@@ -196,6 +187,17 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
196187 else :
197188 result = result .astype (dtype )
198189
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+
199201 return result
200202
201203
0 commit comments