Skip to content

Commit

Permalink
Backport PR #51832 on branch 2.0.x (BUG / CoW: Series.view not respec…
Browse files Browse the repository at this point in the history
…ting CoW) (#51937)

Backport PR #51832: BUG / CoW: Series.view not respecting CoW

Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and phofl committed Mar 13, 2023
1 parent c68fd54 commit 0bbc9f5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ Copy-on-Write improvements
- Arithmetic operations that can be inplace, e.g. ``ser *= 2`` will now respect the
Copy-on-Write mechanism.

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

Copy-on-Write can be enabled through one of

.. code-block:: python
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,10 @@ def view(self, dtype: Dtype | None = None) -> Series:
# implementation
res_values = self.array.view(dtype)
res_ser = self._constructor(res_values, index=self.index)
if isinstance(res_ser._mgr, SingleBlockManager) and using_copy_on_write():
blk = res_ser._mgr._block
blk.refs = cast("BlockValuesRefs", self._references)
blk.refs.add_reference(blk) # type: ignore[arg-type]
return res_ser.__finalize__(self, method="view")

# ----------------------------------------------------------------------
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -1672,3 +1672,21 @@ def test_transpose_ea_single_column(using_copy_on_write):
result = df.T

assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))


def test_series_view(using_copy_on_write):
ser = Series([1, 2, 3])
ser_orig = ser.copy()

ser2 = ser.view()
assert np.shares_memory(get_array(ser), get_array(ser2))
if using_copy_on_write:
assert not ser2._mgr._has_no_reference(0)

ser2.iloc[0] = 100

if using_copy_on_write:
tm.assert_series_equal(ser_orig, ser)
else:
expected = Series([100, 2, 3])
tm.assert_series_equal(ser, expected)

0 comments on commit 0bbc9f5

Please sign in to comment.