diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 80069f1fcacbd..5a0546d8976a9 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1083,11 +1083,8 @@ def setitem(self, indexer, value, using_cow: bool = False) -> Block: # test_iloc_setitem_custom_object casted = setitem_datetimelike_compat(values, len(vi), casted) - if using_cow and self.refs.has_reference(): - values = values.copy() - self = self.make_block_same_class( - values.T if values.ndim == 2 else values - ) + self = self._maybe_copy(using_cow, inplace=True) + values = cast(np.ndarray, self.values.T) if isinstance(casted, np.ndarray) and casted.ndim == 1 and len(casted) == 1: # NumPy 1.25 deprecation: https://github.com/numpy/numpy/pull/10615 casted = casted[0, ...] @@ -1130,14 +1127,10 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: try: casted = np_can_hold_element(values.dtype, new) - if using_cow and self.refs.has_reference(): - # Do this here to avoid copying twice - values = values.copy() - self = self.make_block_same_class(values) + self = self._maybe_copy(using_cow, inplace=True) + values = cast(np.ndarray, self.values) putmask_without_repeat(values.T, mask, casted) - if using_cow: - return [self.copy(deep=False)] return [self] except LossySetitemError: if self.ndim == 1 or self.shape[0] == 1: @@ -1784,10 +1777,6 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: if new is lib.no_default: new = self.fill_value - values = self.values - if values.ndim == 2: - values = values.T - orig_new = new orig_mask = mask new = self._maybe_squeeze_arg(new) @@ -1798,9 +1787,10 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: return [self.copy(deep=False)] return [self] - if using_cow and self.refs.has_reference(): - values = values.copy() - self = self.make_block_same_class(values.T if values.ndim == 2 else values) + self = self._maybe_copy(using_cow, inplace=True) + values = self.values + if values.ndim == 2: + values = values.T try: # Caller is responsible for ensuring matching lengths