Skip to content

REF: simplify _try_cast #41705

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

Merged
merged 3 commits into from
May 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 8 additions & 20 deletions pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
import numpy.ma as ma

from pandas._libs import lib
from pandas._libs.tslibs import (
IncompatibleFrequency,
OutOfBoundsDatetime,
)
from pandas._libs.tslibs import IncompatibleFrequency
from pandas._typing import (
AnyArrayLike,
ArrayLike,
Expand Down Expand Up @@ -719,9 +716,7 @@ def _try_cast(
# while maybe_cast_to_datetime treats it as UTC
# see test_maybe_promote_any_numpy_dtype_with_datetimetz

# error: Incompatible return value type (got "Union[ExtensionArray,
# ndarray, List[Any]]", expected "Union[ExtensionArray, ndarray]")
return maybe_cast_to_datetime(arr, dtype) # type: ignore[return-value]
return maybe_cast_to_datetime(arr, dtype)
# TODO: copy?

array_type = dtype.construct_array_type()._from_sequence
Expand All @@ -734,6 +729,9 @@ def _try_cast(
return subarr
return ensure_wrapped_if_datetimelike(arr).astype(dtype, copy=copy)

elif dtype.kind in ["m", "M"]:
return maybe_cast_to_datetime(arr, dtype)

try:
# GH#15832: Check if we are requesting a numeric dtype and
# that we can convert the data to the requested dtype.
Expand All @@ -743,26 +741,16 @@ def _try_cast(
maybe_cast_to_integer_array(arr, dtype)
subarr = arr
else:
subarr = maybe_cast_to_datetime(arr, dtype)
if dtype is not None and dtype.kind == "M":
return subarr
subarr = arr

if not isinstance(subarr, ABCExtensionArray):
# 4 tests fail if we move this to a try/except/else; see
# test_constructor_compound_dtypes, test_constructor_cast_failure
# test_constructor_dict_cast2, test_loc_setitem_dtype
subarr = construct_1d_ndarray_preserving_na(subarr, dtype, copy=copy)

except OutOfBoundsDatetime:
# in case of out of bound datetime64 -> always raise
raise
except (ValueError, TypeError) as err:
if dtype is not None and raise_cast_failure:
raise
elif "Cannot cast" in str(err) or "cannot be converted to timedelta64" in str(
err
):
# via _disallow_mismatched_datetimelike
except (ValueError, TypeError):
if raise_cast_failure:
raise
else:
subarr = np.array(arr, dtype=object, copy=copy)
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1579,7 +1579,7 @@ def try_timedelta(v: np.ndarray) -> np.ndarray:

def maybe_cast_to_datetime(
value: ExtensionArray | np.ndarray | list, dtype: DtypeObj | None
) -> ExtensionArray | np.ndarray | list:
) -> ExtensionArray | np.ndarray:
"""
try to cast the array/value to a datetimelike dtype, converting float
nan to iNaT
Expand Down Expand Up @@ -1705,7 +1705,8 @@ def maybe_cast_to_datetime(
"maybe_cast_to_datetime allows a list *only* if dtype is not None"
)

return value
# at this point we have converted or raised in all cases where we had a list
return cast(ArrayLike, value)


def sanitize_to_nanoseconds(values: np.ndarray, copy: bool = False) -> np.ndarray:
Expand Down