Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REDO] CLN: core/dtypes/cast.py::maybe_downcast_to_dtype #37126

Merged
merged 11 commits into from
Oct 17, 2020
24 changes: 11 additions & 13 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Routines for casting.
"""

from contextlib import suppress
from datetime import date, datetime, timedelta
from typing import (
TYPE_CHECKING,
Expand Down Expand Up @@ -133,7 +134,7 @@ def is_nested_object(obj) -> bool:
return False


def maybe_downcast_to_dtype(result, dtype: Dtype):
def maybe_downcast_to_dtype(result, dtype: Union[str, np.dtype]):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not correct, DtypeObj right

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

has to be a numpy type or str according to mypy. When I put it DtypeObj mypy errors:

pandas/core/dtypes/cast.py:180: error: Item "ExtensionDtype" of "Union[Any, ExtensionDtype]" has no attribute "freq"  [union-attr]

"""
try to cast to the specified dtype (e.g. convert back to bool/int
or could be an astype of float64->float32
Expand Down Expand Up @@ -169,12 +170,20 @@ def maybe_downcast_to_dtype(result, dtype: 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
Expand All @@ -187,17 +196,6 @@ def maybe_downcast_to_dtype(result, dtype: 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


Expand Down