From ab98a29ac51bf7f8c6d1d50adb3469e76c606ce9 Mon Sep 17 00:00:00 2001 From: Brock Date: Tue, 15 Dec 2020 10:58:44 -0800 Subject: [PATCH] REF: handle ravel inside astype_nansafe --- pandas/core/dtypes/cast.py | 8 ++++++++ pandas/core/internals/blocks.py | 8 +------- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 63445d0e1598d..2f35f34f838ec 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -973,6 +973,14 @@ def astype_nansafe( ValueError The dtype was a datetime64/timedelta64 dtype, but it had no unit. """ + if arr.ndim > 1: + # Make sure we are doing non-copy ravel and reshape. + flags = arr.flags + flat = arr.ravel("K") + result = astype_nansafe(flat, dtype, copy=copy, skipna=skipna) + order = "F" if flags.f_contiguous else "C" + return result.reshape(arr.shape, order=order) + # dispatch on extension dtype if needed if isinstance(dtype, ExtensionDtype): return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index b9558daf05ad2..2630c07814bb2 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -629,10 +629,6 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): else: raise - if isinstance(new_values, np.ndarray): - # TODO(EA2D): special case not needed with 2D EAs - new_values = new_values.reshape(self.shape) - newb = self.make_block(new_values) if newb.is_numeric and self.is_numeric: if newb.shape != self.shape: @@ -691,9 +687,7 @@ def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike: # We still need to go through astype_nansafe for # e.g. dtype = Sparse[object, 0] - # astype_nansafe works with 1-d only - vals1d = values.ravel() - values = astype_nansafe(vals1d, dtype, copy=True) + values = astype_nansafe(values, dtype, copy=True) return values