Skip to content

Commit

Permalink
Backport PR #52040 on branch 2.0.x (CoW: Optimize Series.reset_index …
Browse files Browse the repository at this point in the history
…to make lazy copy) (#52050)

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

Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and phofl committed Mar 17, 2023
1 parent 285a5aa commit a38514e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1584,6 +1584,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

0 comments on commit a38514e

Please sign in to comment.