@@ -147,6 +147,13 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
147
147
elif isinstance (result , ABCDataFrame ):
148
148
# occurs in pivot_table doctest
149
149
return result
150
+ elif is_period_dtype (dtype ):
151
+ from pandas .core .arrays import PeriodArray
152
+
153
+ with suppress (TypeError ):
154
+ # e.g. TypeError: int() argument must be a string, a
155
+ # bytes-like object or a number, not 'Period
156
+ return PeriodArray (result , freq = dtype .freq )
150
157
151
158
if isinstance (dtype , str ):
152
159
if dtype == "infer" :
@@ -178,25 +185,17 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
178
185
# a datetimelike
179
186
# GH12821, iNaT is cast to float
180
187
if is_datetime_or_timedelta_any_dtype (dtype ) and result .dtype .kind in ["i" , "f" ]:
181
- if not is_datetime_or_timedelta_dtype (dtype ):
188
+
189
+ if is_datetime_or_timedelta_dtype (dtype ):
190
+ result = result .astype (dtype )
191
+ else :
182
192
# not a numpy dtype
183
193
if dtype .tz :
184
194
# convert to datetime and change timezone
185
195
from pandas import to_datetime
186
196
187
197
result = to_datetime (result ).tz_localize ("utc" )
188
198
result = result .tz_convert (dtype .tz )
189
- else :
190
- result = result .astype (dtype )
191
-
192
- elif is_period_dtype (dtype ):
193
- # TODO(DatetimeArray): merge with previous elif
194
- from pandas .core .arrays import PeriodArray
195
-
196
- with suppress (TypeError ):
197
- # e.g. TypeError: int() argument must be a string, a
198
- # bytes-like object or a number, not 'Period
199
- return PeriodArray (result , freq = dtype .freq )
200
199
201
200
return result
202
201
0 commit comments