From 3e8ac12d1dacc2308b2f4c2869fa7bc2079bd323 Mon Sep 17 00:00:00 2001 From: Joris Van den Bossche Date: Sun, 15 Sep 2024 22:00:26 +0200 Subject: [PATCH] BUG (CoW): fix reference tracking in replace_list with None (#59807) --- pandas/core/internals/blocks.py | 2 +- pandas/tests/copy_view/test_replace.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index dced92ba04520..cb40e920149fa 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -915,7 +915,7 @@ def _replace_coerce( nb = nb.copy() putmask_inplace(nb.values, mask, value) return [nb] - return [self] + return [self.copy(deep=False)] return self.replace( to_replace=to_replace, value=value, diff --git a/pandas/tests/copy_view/test_replace.py b/pandas/tests/copy_view/test_replace.py index 58c979fb05089..a8acd446ff5f5 100644 --- a/pandas/tests/copy_view/test_replace.py +++ b/pandas/tests/copy_view/test_replace.py @@ -286,6 +286,12 @@ def test_replace_list_none(): assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + # replace multiple values that don't actually replace anything with None + # https://github.com/pandas-dev/pandas/issues/59770 + df3 = df.replace(["d", "e", "f"], value=None) + tm.assert_frame_equal(df3, df_orig) + assert tm.shares_memory(get_array(df, "a"), get_array(df3, "a")) + def test_replace_list_none_inplace_refs(): df = DataFrame({"a": ["a", "b", "c"]})