Skip to content
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

ENH/CoW: use lazy copy in set_index method #49557

Merged
merged 3 commits into from
Nov 15, 2022
Merged
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
3 changes: 2 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5855,7 +5855,8 @@ def set_index(
if inplace:
frame = self
else:
frame = self.copy()
# GH 49473 Use "lazy copy" with Copy-on-Write
frame = self.copy(deep=None)

arrays = []
names: list[Hashable] = []
Expand Down
17 changes: 17 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,20 @@ 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_set_index(using_copy_on_write):
# GH 49473
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
df_orig = df.copy()
df2 = df.set_index("a")

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

# mutating df2 triggers a copy-on-write for that column / block
df2.iloc[0, 1] = 0
assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c"))
tm.assert_frame_equal(df, df_orig)