Skip to content

Backport PR #51950 on branch 2.0.x (BUG: Series.getitem not respecting CoW with MultiIndex) #52005

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,9 @@ Copy-on-Write improvements
- :meth:`DataFrame.__getitem__` will now respect the Copy-on-Write mechanism when the
:class:`DataFrame` has :class:`MultiIndex` columns.

- :meth:`Series.__getitem__` will now respect the Copy-on-Write mechanism when the
:class:`Series` has a :class:`MultiIndex`.

- :meth:`Series.view` will now respect the Copy-on-Write mechanism.

Copy-on-Write can be enabled through one of
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1113,6 +1113,8 @@ def _get_value(self, label, takeable: bool = False):
new_index = mi[loc]
new_index = maybe_droplevels(new_index, label)
new_ser = self._constructor(new_values, index=new_index, name=self.name)
if using_copy_on_write() and isinstance(loc, slice):
new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type]
return new_ser.__finalize__(self)

else:
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/copy_view/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1036,6 +1036,18 @@ def test_set_value_copy_only_necessary_column(
assert np.shares_memory(get_array(df, "a"), get_array(view, "a"))


def test_series_midx_slice(using_copy_on_write):
ser = Series([1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]]))
result = ser[1]
assert np.shares_memory(get_array(ser), get_array(result))
result.iloc[0] = 100
if using_copy_on_write:
expected = Series(
[1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]])
)
tm.assert_series_equal(ser, expected)


def test_getitem_midx_slice(using_copy_on_write, using_array_manager):
df = DataFrame({("a", "x"): [1, 2], ("a", "y"): 1, ("b", "x"): 2})
df_orig = df.copy()
Expand Down