@@ -132,6 +132,13 @@ def maybe_downcast_to_dtype(result, dtype):
132132 elif isinstance (result , ABCDataFrame ):
133133 # occurs in pivot_table doctest
134134 return result
135+ elif is_period_dtype (dtype ):
136+ from pandas .core .arrays import PeriodArray
137+
138+ with suppress (TypeError ):
139+ # e.g. TypeError: int() argument must be a string, a
140+ # bytes-like object or a number, not 'Period
141+ return PeriodArray (result , freq = dtype .freq )
135142
136143 if isinstance (dtype , str ):
137144 if dtype == "infer" :
@@ -163,25 +170,17 @@ def maybe_downcast_to_dtype(result, dtype):
163170 # a datetimelike
164171 # GH12821, iNaT is cast to float
165172 if is_datetime_or_timedelta_any_dtype (dtype ) and result .dtype .kind in ["i" , "f" ]:
166- if not is_datetime_or_timedelta_dtype (dtype ):
173+
174+ if is_datetime_or_timedelta_dtype (dtype ):
175+ result = result .astype (dtype )
176+ else :
167177 # not a numpy dtype
168178 if dtype .tz :
169179 # convert to datetime and change timezone
170180 from pandas import to_datetime
171181
172182 result = to_datetime (result ).tz_localize ("utc" )
173183 result = result .tz_convert (dtype .tz )
174- else :
175- result = result .astype (dtype )
176-
177- elif is_period_dtype (dtype ):
178- # TODO(DatetimeArray): merge with previous elif
179- from pandas .core .arrays import PeriodArray
180-
181- with suppress (TypeError ):
182- # e.g. TypeError: int() argument must be a string, a
183- # bytes-like object or a number, not 'Period
184- return PeriodArray (result , freq = dtype .freq )
185184
186185 return result
187186
0 commit comments