From e8f011176ff740bae322e80cf68e9a4a3c68056d Mon Sep 17 00:00:00 2001 From: Marco Gorelli Date: Mon, 18 Jan 2021 16:57:14 +0000 Subject: [PATCH 1/2] refactor maybe-castable --- pandas/core/construction.py | 10 +++++++--- pandas/core/dtypes/cast.py | 12 +++++------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 54a6f47ae1b38..293d31dd19523 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -584,9 +584,13 @@ def _try_cast(arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bo Otherwise an object array is returned. """ # perf shortcut as this is the most common case - if isinstance(arr, np.ndarray): - if maybe_castable(arr) and not copy and dtype is None: - return arr + if ( + isinstance(arr, np.ndarray) + and maybe_castable(arr.dtype) + and not copy + and dtype is None + ): + return arr if isinstance(dtype, ExtensionDtype) and (dtype.kind != "M" or is_sparse(dtype)): # create an extension array from its dtype diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 0941967ef6bee..e9b3238a74186 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1301,20 +1301,18 @@ def convert_dtypes( return inferred_dtype -def maybe_castable(arr: np.ndarray) -> bool: +def maybe_castable(dtype: DtypeObj) -> bool: # return False to force a non-fastpath - assert isinstance(arr, np.ndarray) # GH 37024 - # check datetime64[ns]/timedelta64[ns] are valid # otherwise try to coerce - kind = arr.dtype.kind + kind = dtype.kind if kind == "M": - return is_datetime64_ns_dtype(arr.dtype) + return is_datetime64_ns_dtype(dtype) elif kind == "m": - return is_timedelta64_ns_dtype(arr.dtype) + return is_timedelta64_ns_dtype(dtype) - return arr.dtype.name not in POSSIBLY_CAST_DTYPES + return dtype.name not in POSSIBLY_CAST_DTYPES def maybe_infer_to_datetimelike( From eb1dd2cb8286a066be909b6afefc0ac4758c033d Mon Sep 17 00:00:00 2001 From: Marco Gorelli Date: Sun, 31 Jan 2021 16:41:07 +0000 Subject: [PATCH 2/2] DtypeObj -> np.dtype --- pandas/core/dtypes/cast.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 00c008de8dd05..12fa5d40d6ab9 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1331,7 +1331,7 @@ def convert_dtypes( return inferred_dtype -def maybe_castable(dtype: DtypeObj) -> bool: +def maybe_castable(dtype: np.dtype) -> bool: # return False to force a non-fastpath # check datetime64[ns]/timedelta64[ns] are valid