Skip to content

ENH/CoW: use lazy copy on replace method #49555

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7213,6 +7213,8 @@ def replace(
if inplace:
return self._update_inplace(result)
else:
# GH 49473 Use "lazy copy" with Copy-on-Write
result = self.copy(deep=None)
return result.__finalize__(self, method="replace")

def interpolate(
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,21 @@ def test_chained_methods(request, method, idx, using_copy_on_write):
df.iloc[0, 0] = 0
if not df2_is_view:
tm.assert_frame_equal(df2.iloc[:, idx:], df_orig)


def test_replace(using_copy_on_write):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
df_orig = df.copy()
df2 = df.replace(1, 5)
df2._mgr._verify_integrity()

if using_copy_on_write:
assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
else:
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))

# mutating df2 triggers a copy-on-write for that column/block
df2.iloc[0, 0] = 0
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)