Skip to content

CoW: Optimize Series.reset_index to make lazy copy #52040

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

Merged
merged 3 commits into from
Mar 17, 2023
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
4 changes: 4 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1550,6 +1550,10 @@ def reset_index(

if inplace:
self.index = new_index
elif using_copy_on_write():
new_ser = self.copy(deep=False)
new_ser.index = new_index
return new_ser.__finalize__(self, method="reset_index")
else:
return self._constructor(
self._values.copy(), index=new_index, copy=False
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,21 @@ def test_reset_index(using_copy_on_write):
tm.assert_frame_equal(df, df_orig)


@pytest.mark.parametrize("index", [pd.RangeIndex(0, 2), Index([1, 2])])
def test_reset_index_series_drop(using_copy_on_write, index):
ser = Series([1, 2], index=index)
ser_orig = ser.copy()
ser2 = ser.reset_index(drop=True)
if using_copy_on_write:
assert np.shares_memory(get_array(ser), get_array(ser2))
assert not ser._mgr._has_no_reference(0)
else:
assert not np.shares_memory(get_array(ser), get_array(ser2))

ser2.iloc[0] = 100
tm.assert_series_equal(ser, ser_orig)


def test_rename_columns(using_copy_on_write):
# Case: renaming columns returns a new dataframe
# + afterwards modifying the result
Expand Down