Skip to content

Commit b8035bb

Browse files
authored
REF: collect casting portion of Block.setitem (#32940)
1 parent b8004b8 commit b8035bb

File tree

1 file changed

+12
-18
lines changed

1 file changed

+12
-18
lines changed

pandas/core/internals/blocks.py

+12-18
Original file line numberDiff line numberDiff line change
@@ -833,21 +833,24 @@ def setitem(self, indexer, value):
833833

834834
else:
835835
# current dtype cannot store value, coerce to common dtype
836-
find_dtype = False
837836

838837
if hasattr(value, "dtype"):
839838
dtype = value.dtype
840-
find_dtype = True
841839

842840
elif lib.is_scalar(value) and not isna(value):
843841
dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)
844-
find_dtype = True
845842

846-
if find_dtype:
847-
dtype = find_common_type([values.dtype, dtype])
848-
if not is_dtype_equal(self.dtype, dtype):
849-
b = self.astype(dtype)
850-
return b.setitem(indexer, value)
843+
else:
844+
# e.g. we are bool dtype and value is nan
845+
# TODO: watch out for case with listlike value and scalar/empty indexer
846+
dtype, _ = maybe_promote(np.array(value).dtype)
847+
return self.astype(dtype).setitem(indexer, value)
848+
849+
dtype = find_common_type([values.dtype, dtype])
850+
assert not is_dtype_equal(self.dtype, dtype)
851+
# otherwise should have _can_hold_element
852+
853+
return self.astype(dtype).setitem(indexer, value)
851854

852855
# value must be storeable at this moment
853856
if is_extension_array_dtype(getattr(value, "dtype", None)):
@@ -857,11 +860,6 @@ def setitem(self, indexer, value):
857860
else:
858861
arr_value = np.array(value)
859862

860-
# cast the values to a type that can hold nan (if necessary)
861-
if not self._can_hold_element(value):
862-
dtype, _ = maybe_promote(arr_value.dtype)
863-
values = values.astype(dtype)
864-
865863
if transpose:
866864
values = values.T
867865

@@ -881,11 +879,7 @@ def setitem(self, indexer, value):
881879
# be e.g. a list; see GH#6043
882880
values[indexer] = value
883881

884-
elif (
885-
exact_match
886-
and is_categorical_dtype(arr_value.dtype)
887-
and not is_categorical_dtype(values)
888-
):
882+
elif exact_match and is_categorical_dtype(arr_value.dtype):
889883
# GH25495 - If the current dtype is not categorical,
890884
# we need to create a new categorical block
891885
values[indexer] = value

0 commit comments

Comments
 (0)