diff --git a/pandas/core/frame.py b/pandas/core/frame.py index dbbe2c0751f3a..b8632a52f8988 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4105,9 +4105,11 @@ def _set_item_mgr(self, key, value: ArrayLike) -> None: if len(self): self._check_setitem_copy() - def _iset_item(self, loc: int, value) -> None: - arraylike = self._sanitize_column(value) - self._iset_item_mgr(loc, arraylike, inplace=True) + def _iset_item(self, loc: int, value: Series) -> None: + # We are only called from _replace_columnwise which guarantees that + # no reindex is necessary + # TODO(CoW): Optimize to avoid copy here, but have ton track refs + self._iset_item_mgr(loc, value._values.copy(), inplace=True) # check if we are modifying a copy # try to set first as we want an invalid diff --git a/pandas/tests/copy_view/test_replace.py b/pandas/tests/copy_view/test_replace.py index c0b5498b839f5..dfb1caa4b2ffd 100644 --- a/pandas/tests/copy_view/test_replace.py +++ b/pandas/tests/copy_view/test_replace.py @@ -362,3 +362,14 @@ def test_replace_list_none_inplace_refs(using_copy_on_write): tm.assert_frame_equal(df_orig, view) else: assert np.shares_memory(arr, get_array(df, "a")) + + +def test_replace_columnwise_no_op(using_copy_on_write): + df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]}) + df_orig = df.copy() + df2 = df.replace({"a": 10}, 100) + if using_copy_on_write: + # TODO(CoW): This should share memory + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + df2.iloc[0, 0] = 100 + tm.assert_frame_equal(df, df_orig)