@@ -132,6 +132,13 @@ def maybe_downcast_to_dtype(result, dtype):
132
132
elif isinstance (result , ABCDataFrame ):
133
133
# occurs in pivot_table doctest
134
134
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 )
135
142
136
143
if isinstance (dtype , str ):
137
144
if dtype == "infer" :
@@ -163,25 +170,17 @@ def maybe_downcast_to_dtype(result, dtype):
163
170
# a datetimelike
164
171
# GH12821, iNaT is cast to float
165
172
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 :
167
177
# not a numpy dtype
168
178
if dtype .tz :
169
179
# convert to datetime and change timezone
170
180
from pandas import to_datetime
171
181
172
182
result = to_datetime (result ).tz_localize ("utc" )
173
183
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 )
185
184
186
185
return result
187
186
0 commit comments