Skip to content

Commit f07ef46

Browse files
phoflmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#52040: CoW: Optimize Series.reset_index to make lazy copy
1 parent a498448 commit f07ef46

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

pandas/core/series.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1579,6 +1579,10 @@ def reset_index(
15791579

15801580
if inplace:
15811581
self.index = new_index
1582+
elif using_copy_on_write():
1583+
new_ser = self.copy(deep=False)
1584+
new_ser.index = new_index
1585+
return new_ser.__finalize__(self, method="reset_index")
15821586
else:
15831587
return self._constructor(
15841588
self._values.copy(), index=new_index, copy=False

pandas/tests/copy_view/test_methods.py

Lines changed: 15 additions & 0 deletions
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)