diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9534eca51f383..6e2fd68b60a54 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -740,7 +740,8 @@ def _set_axis_nocheck(self, labels, axis: Axis, inplace: bool_t, copy: bool_t): else: # With copy=False, we create a new object but don't copy the # underlying data. - obj = self.copy(deep=copy) + if copy: + obj = self.copy(deep=None) setattr(obj, obj._get_axis_name(axis), labels) return obj diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index f5c7b31e59bc5..4d0a225086e5d 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -321,6 +321,21 @@ def test_head_tail(method, using_copy_on_write): df2.iloc[0, 0] = 1 tm.assert_frame_equal(df, df_orig) +def test_droplevel(using_copy_on_write): + # GH 49473 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}).set_index(["a","b"]) + df_orig = df.copy() + df2 = df.droplevel(0) + + if using_copy_on_write: + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + else: + assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + + # mutating df2 triggers a copy-on-write for that column / block + df2.loc["b","c"] = 1 + + def test_assign(using_copy_on_write): df = DataFrame({"a": [1, 2, 3]}) @@ -356,3 +371,6 @@ def test_reorder_levels(using_copy_on_write): if using_copy_on_write: assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) tm.assert_frame_equal(df, df_orig) + + assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + tm.assert_frame_equal(df, df_orig)