Skip to content

Commit a49bedb

Browse files
Backport PR #52001 on branch 2.0.x (BUG - CoW: Series with MultiIndex with tuples does not respect CoW) (#52009)
Backport PR #52001: BUG - CoW: Series with MultiIndex with tuples does not respect CoW Co-authored-by: Patrick Hoefler <[email protected]>
1 parent fbc660b commit a49bedb

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

pandas/core/series.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1073,9 +1073,10 @@ def _get_values_tuple(self, key: tuple):
10731073

10741074
# If key is contained, would have returned by now
10751075
indexer, new_index = self.index.get_loc_level(key)
1076-
return self._constructor(self._values[indexer], index=new_index).__finalize__(
1077-
self
1078-
)
1076+
new_ser = self._constructor(self._values[indexer], index=new_index)
1077+
if using_copy_on_write() and isinstance(indexer, slice):
1078+
new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type]
1079+
return new_ser.__finalize__(self)
10791080

10801081
def _get_values(self, indexer: slice | npt.NDArray[np.bool_]) -> Series:
10811082
new_mgr = self._mgr.getitem_mgr(indexer)

pandas/tests/copy_view/test_indexing.py

+16
Original file line numberDiff line numberDiff line change
@@ -1061,3 +1061,19 @@ def test_getitem_midx_slice(using_copy_on_write, using_array_manager):
10611061
if using_copy_on_write:
10621062
new_df.iloc[0, 0] = 100
10631063
tm.assert_frame_equal(df_orig, df)
1064+
1065+
1066+
def test_series_midx_tuples_slice(using_copy_on_write):
1067+
ser = Series(
1068+
[1, 2, 3],
1069+
index=pd.MultiIndex.from_tuples([((1, 2), 3), ((1, 2), 4), ((2, 3), 4)]),
1070+
)
1071+
result = ser[(1, 2)]
1072+
assert np.shares_memory(get_array(ser), get_array(result))
1073+
result.iloc[0] = 100
1074+
if using_copy_on_write:
1075+
expected = Series(
1076+
[1, 2, 3],
1077+
index=pd.MultiIndex.from_tuples([((1, 2), 3), ((1, 2), 4), ((2, 3), 4)]),
1078+
)
1079+
tm.assert_series_equal(ser, expected)

0 commit comments

Comments
 (0)