Skip to content

Commit a38514e

Browse files
Backport PR #52040 on branch 2.0.x (CoW: Optimize Series.reset_index to make lazy copy) (#52050)
Backport PR #52040: CoW: Optimize Series.reset_index to make lazy copy Co-authored-by: Patrick Hoefler <[email protected]>
1 parent 285a5aa commit a38514e

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

pandas/core/series.py

+4
Original file line numberDiff line numberDiff line change
@@ -1584,6 +1584,10 @@ def reset_index(
15841584

15851585
if inplace:
15861586
self.index = new_index
1587+
elif using_copy_on_write():
1588+
new_ser = self.copy(deep=False)
1589+
new_ser.index = new_index
1590+
return new_ser.__finalize__(self, method="reset_index")
15871591
else:
15881592
return self._constructor(
15891593
self._values.copy(), index=new_index, copy=False

pandas/tests/copy_view/test_methods.py

+15
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,21 @@ def test_reset_index(using_copy_on_write):
233233
tm.assert_frame_equal(df, df_orig)
234234

235235

236+
@pytest.mark.parametrize("index", [pd.RangeIndex(0, 2), Index([1, 2])])
237+
def test_reset_index_series_drop(using_copy_on_write, index):
238+
ser = Series([1, 2], index=index)
239+
ser_orig = ser.copy()
240+
ser2 = ser.reset_index(drop=True)
241+
if using_copy_on_write:
242+
assert np.shares_memory(get_array(ser), get_array(ser2))
243+
assert not ser._mgr._has_no_reference(0)
244+
else:
245+
assert not np.shares_memory(get_array(ser), get_array(ser2))
246+
247+
ser2.iloc[0] = 100
248+
tm.assert_series_equal(ser, ser_orig)
249+
250+
236251
def test_rename_columns(using_copy_on_write):
237252
# Case: renaming columns returns a new dataframe
238253
# + afterwards modifying the result

0 commit comments

Comments
 (0)