From 0bf763d6386596c1f1869034e6330c3c704a2e7f Mon Sep 17 00:00:00 2001 From: Brock Date: Thu, 24 Dec 2020 07:23:43 -0800 Subject: [PATCH] REF: simplify coerce_to_target_dtype --- pandas/core/internals/blocks.py | 33 +++------------------------------ 1 file changed, 3 insertions(+), 30 deletions(-) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 27acd720b6d71..79db2c449d484 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -39,9 +39,7 @@ from pandas.core.dtypes.common import ( DT64NS_DTYPE, TD64NS_DTYPE, - is_bool_dtype, is_categorical_dtype, - is_datetime64_any_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_dtype_equal, @@ -55,7 +53,6 @@ is_re, is_re_compilable, is_sparse, - is_timedelta64_dtype, pandas_dtype, ) from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype @@ -924,7 +921,7 @@ def setitem(self, indexer, value): else: # current dtype cannot store value, coerce to common dtype - + # TODO: can we just use coerce_to_target_dtype for all this if hasattr(value, "dtype"): dtype = value.dtype @@ -1167,33 +1164,9 @@ def coerce_to_target_dtype(self, other): # if we cannot then coerce to object dtype, _ = infer_dtype_from(other, pandas_dtype=True) - if is_dtype_equal(self.dtype, dtype): - return self - - if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype): - # we don't upcast to bool - return self.astype(object) - - elif (self.is_float or self.is_complex) and ( - is_integer_dtype(dtype) or is_float_dtype(dtype) - ): - # don't coerce float/complex to int - return self + new_dtype = find_common_type([self.dtype, dtype]) - elif self.is_datetime or is_datetime64_any_dtype(dtype): - # The is_dtype_equal check above ensures that at most one of - # these two conditions hold, so we must cast to object. - return self.astype(object) - - elif self.is_timedelta or is_timedelta64_dtype(dtype): - # The is_dtype_equal check above ensures that at most one of - # these two conditions hold, so we must cast to object. - return self.astype(object) - - try: - return self.astype(dtype) - except (ValueError, TypeError, OverflowError): - return self.astype(object) + return self.astype(new_dtype, copy=False) def interpolate( self,