Skip to content

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

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 1 commit into from
Mar 13, 2023
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
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 @@ -837,6 +837,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 @@ -1597,3 +1597,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)