Skip to content

Commit 98011a9

Browse files
authored
[REDO] CLN: core/dtypes/cast.py::maybe_downcast_to_dtype (#37126)
1 parent 0013472 commit 98011a9

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

pandas/core/dtypes/cast.py

+11-13
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Routines for casting.
33
"""
44

5+
from contextlib import suppress
56
from datetime import date, datetime, timedelta
67
from typing import (
78
TYPE_CHECKING,
@@ -133,7 +134,7 @@ def is_nested_object(obj) -> bool:
133134
return False
134135

135136

136-
def maybe_downcast_to_dtype(result, dtype: Dtype):
137+
def maybe_downcast_to_dtype(result, dtype: Union[str, np.dtype]):
137138
"""
138139
try to cast to the specified dtype (e.g. convert back to bool/int
139140
or could be an astype of float64->float32
@@ -169,12 +170,20 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
169170

170171
dtype = np.dtype(dtype)
171172

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+
172181
converted = maybe_downcast_numeric(result, dtype, do_round)
173182
if converted is not result:
174183
return converted
175184

176185
# a datetimelike
177-
# GH12821, iNaT is casted to float
186+
# GH12821, iNaT is cast to float
178187
if dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]:
179188
if hasattr(dtype, "tz"):
180189
# not a numpy dtype
@@ -187,17 +196,6 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
187196
else:
188197
result = result.astype(dtype)
189198

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-
201199
return result
202200

203201

0 commit comments

Comments
 (0)