Skip to content

Commit a083567

Browse files
authored
BUG: Series.getitem not respecting CoW with MultiIndex (#51950)
1 parent 6a13450 commit a083567

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

doc/source/whatsnew/v2.0.0.rst

+3
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,9 @@ Copy-on-Write improvements
209209
- :meth:`DataFrame.__getitem__` will now respect the Copy-on-Write mechanism when the
210210
:class:`DataFrame` has :class:`MultiIndex` columns.
211211

212+
- :meth:`Series.__getitem__` will now respect the Copy-on-Write mechanism when the
213+
:class:`Series` has a :class:`MultiIndex`.
214+
212215
- :meth:`Series.view` will now respect the Copy-on-Write mechanism.
213216

214217
Copy-on-Write can be enabled through one of

pandas/core/series.py

+2
Original file line numberDiff line numberDiff line change
@@ -1084,6 +1084,8 @@ def _get_value(self, label, takeable: bool = False):
10841084
new_index = mi[loc]
10851085
new_index = maybe_droplevels(new_index, label)
10861086
new_ser = self._constructor(new_values, index=new_index, name=self.name)
1087+
if using_copy_on_write() and isinstance(loc, slice):
1088+
new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type]
10871089
return new_ser.__finalize__(self)
10881090

10891091
else:

pandas/tests/copy_view/test_indexing.py

+12
Original file line numberDiff line numberDiff line change
@@ -1036,6 +1036,18 @@ def test_set_value_copy_only_necessary_column(
10361036
assert np.shares_memory(get_array(df, "a"), get_array(view, "a"))
10371037

10381038

1039+
def test_series_midx_slice(using_copy_on_write):
1040+
ser = Series([1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]]))
1041+
result = ser[1]
1042+
assert np.shares_memory(get_array(ser), get_array(result))
1043+
result.iloc[0] = 100
1044+
if using_copy_on_write:
1045+
expected = Series(
1046+
[1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]])
1047+
)
1048+
tm.assert_series_equal(ser, expected)
1049+
1050+
10391051
def test_getitem_midx_slice(using_copy_on_write, using_array_manager):
10401052
df = DataFrame({("a", "x"): [1, 2], ("a", "y"): 1, ("b", "x"): 2})
10411053
df_orig = df.copy()

0 commit comments

Comments
 (0)