From c9f998c2b3fa677e325344d0d1737cc6be60a768 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler Date: Thu, 29 Dec 2022 22:04:28 +0100 Subject: [PATCH 1/2] ENH: Add lazy copy for sort_index --- pandas/conftest.py | 1 + pandas/core/generic.py | 2 +- pandas/tests/copy_view/test_methods.py | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/pandas/conftest.py b/pandas/conftest.py index 3b167d9ef4fe2..14c4e59778c9a 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1903,6 +1903,7 @@ def using_copy_on_write() -> bool: """ Fixture to check if Copy-on-Write is enabled. """ + pd.options.mode.copy_on_write = True return pd.options.mode.copy_on_write and pd.options.mode.data_manager == "block" diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c893e9ce3d9a9..23eb66abb8561 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4934,7 +4934,7 @@ def sort_index( if inplace: result = self else: - result = self.copy() + result = self.copy(deep=None) if ignore_index: result.index = default_index(len(self)) diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 878f1d8089d33..dc0bf01c84c74 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -405,6 +405,23 @@ def test_reindex_like(using_copy_on_write): tm.assert_frame_equal(df, df_orig) +def test_sort_index(using_copy_on_write): + # GH 49473 + ser = Series([1, 2, 3]) + ser_orig = ser.copy() + ser2 = ser.sort_index() + + if using_copy_on_write: + assert np.shares_memory(ser.values, ser2.values) + else: + assert not np.shares_memory(ser.values, ser2.values) + + # mutating ser triggers a copy-on-write for the column / block + ser2.iloc[0] = 0 + assert not np.shares_memory(ser2.values, ser.values) + tm.assert_series_equal(ser, ser_orig) + + def test_reorder_levels(using_copy_on_write): index = MultiIndex.from_tuples( [(1, 1), (1, 2), (2, 1), (2, 2)], names=["one", "two"] From 0a5c9e675930d552ad9e66584a865060fb332062 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Tue, 3 Jan 2023 09:57:12 +0100 Subject: [PATCH 2/2] Update conftest.py --- pandas/conftest.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pandas/conftest.py b/pandas/conftest.py index 14c4e59778c9a..3b167d9ef4fe2 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1903,7 +1903,6 @@ def using_copy_on_write() -> bool: """ Fixture to check if Copy-on-Write is enabled. """ - pd.options.mode.copy_on_write = True return pd.options.mode.copy_on_write and pd.options.mode.data_manager == "block"