Skip to content

Commit 90a76ce

Browse files
committed
REF: simplify coerce_to_target_dtype (pandas-dev#38683)
1 parent 5896615 commit 90a76ce

File tree

1 file changed

+3
-30
lines changed

1 file changed

+3
-30
lines changed

pandas/core/internals/blocks.py

+3-30
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,7 @@
3737
from pandas.core.dtypes.common import (
3838
DT64NS_DTYPE,
3939
TD64NS_DTYPE,
40-
is_bool_dtype,
4140
is_categorical_dtype,
42-
is_datetime64_any_dtype,
4341
is_datetime64_dtype,
4442
is_datetime64tz_dtype,
4543
is_dtype_equal,
@@ -53,7 +51,6 @@
5351
is_re,
5452
is_re_compilable,
5553
is_sparse,
56-
is_timedelta64_dtype,
5754
pandas_dtype,
5855
)
5956
from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype
@@ -927,7 +924,7 @@ def setitem(self, indexer, value):
927924

928925
else:
929926
# current dtype cannot store value, coerce to common dtype
930-
927+
# TODO: can we just use coerce_to_target_dtype for all this
931928
if hasattr(value, "dtype"):
932929
dtype = value.dtype
933930

@@ -1164,33 +1161,9 @@ def coerce_to_target_dtype(self, other):
11641161
# if we cannot then coerce to object
11651162
dtype, _ = infer_dtype_from(other, pandas_dtype=True)
11661163

1167-
if is_dtype_equal(self.dtype, dtype):
1168-
return self
1169-
1170-
if self.is_bool or is_object_dtype(dtype) or is_bool_dtype(dtype):
1171-
# we don't upcast to bool
1172-
return self.astype(object)
1173-
1174-
elif (self.is_float or self.is_complex) and (
1175-
is_integer_dtype(dtype) or is_float_dtype(dtype)
1176-
):
1177-
# don't coerce float/complex to int
1178-
return self
1164+
new_dtype = find_common_type([self.dtype, dtype])
11791165

1180-
elif self.is_datetime or is_datetime64_any_dtype(dtype):
1181-
# The is_dtype_equal check above ensures that at most one of
1182-
# these two conditions hold, so we must cast to object.
1183-
return self.astype(object)
1184-
1185-
elif self.is_timedelta or is_timedelta64_dtype(dtype):
1186-
# The is_dtype_equal check above ensures that at most one of
1187-
# these two conditions hold, so we must cast to object.
1188-
return self.astype(object)
1189-
1190-
try:
1191-
return self.astype(dtype)
1192-
except (ValueError, TypeError, OverflowError):
1193-
return self.astype(object)
1166+
return self.astype(new_dtype, copy=False)
11941167

11951168
def interpolate(
11961169
self,

0 commit comments

Comments
 (0)