From fad14fd73a66ce6c821f927b49c6e9b57b868c20 Mon Sep 17 00:00:00 2001 From: Andrew Wieteska <48889395+arw2019@users.noreply.github.com> Date: Wed, 14 Oct 2020 08:32:42 -0400 Subject: [PATCH] CLN: core/dtypes/cast.py::maybe_downcast_to_dtype (#37050) --- pandas/core/dtypes/cast.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 7c76d02f59392..74a607ab14d06 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -2,6 +2,7 @@ Routines for casting. """ +from contextlib import suppress from datetime import date, datetime, timedelta from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type @@ -156,12 +157,20 @@ def maybe_downcast_to_dtype(result, dtype): dtype = np.dtype(dtype) + elif dtype.type is Period: + from pandas.core.arrays import PeriodArray + + with suppress(TypeError): + # e.g. TypeError: int() argument must be a string, a + # bytes-like object or a number, not 'Period + return PeriodArray(result, freq=dtype.freq) + converted = maybe_downcast_numeric(result, dtype, do_round) if converted is not result: return converted # a datetimelike - # GH12821, iNaT is casted to float + # GH12821, iNaT is cast to float if dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]: if hasattr(dtype, "tz"): # not a numpy dtype @@ -174,17 +183,6 @@ def maybe_downcast_to_dtype(result, dtype): else: result = result.astype(dtype) - elif dtype.type is Period: - # TODO(DatetimeArray): merge with previous elif - from pandas.core.arrays import PeriodArray - - try: - return PeriodArray(result, freq=dtype.freq) - except TypeError: - # e.g. TypeError: int() argument must be a string, a - # bytes-like object or a number, not 'Period - pass - return result