Skip to content

Commit 26b17c2

Browse files
authored
BUG / CoW: Series.view not respecting CoW (#51832)
1 parent ab76540 commit 26b17c2

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

doc/source/whatsnew/v2.0.0.rst

+2
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,8 @@ Copy-on-Write improvements
206206
- Arithmetic operations that can be inplace, e.g. ``ser *= 2`` will now respect the
207207
Copy-on-Write mechanism.
208208

209+
- :meth:`Series.view` will now respect the Copy-on-Write mechanism.
210+
209211
Copy-on-Write can be enabled through one of
210212

211213
.. code-block:: python

pandas/core/series.py

+4
Original file line numberDiff line numberDiff line change
@@ -839,6 +839,10 @@ def view(self, dtype: Dtype | None = None) -> Series:
839839
# implementation
840840
res_values = self.array.view(dtype)
841841
res_ser = self._constructor(res_values, index=self.index)
842+
if isinstance(res_ser._mgr, SingleBlockManager) and using_copy_on_write():
843+
blk = res_ser._mgr._block
844+
blk.refs = cast("BlockValuesRefs", self._references)
845+
blk.refs.add_reference(blk) # type: ignore[arg-type]
842846
return res_ser.__finalize__(self, method="view")
843847

844848
# ----------------------------------------------------------------------

pandas/tests/copy_view/test_methods.py

+18
Original file line numberDiff line numberDiff line change
@@ -1672,3 +1672,21 @@ def test_transpose_ea_single_column(using_copy_on_write):
16721672
result = df.T
16731673

16741674
assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))
1675+
1676+
1677+
def test_series_view(using_copy_on_write):
1678+
ser = Series([1, 2, 3])
1679+
ser_orig = ser.copy()
1680+
1681+
ser2 = ser.view()
1682+
assert np.shares_memory(get_array(ser), get_array(ser2))
1683+
if using_copy_on_write:
1684+
assert not ser2._mgr._has_no_reference(0)
1685+
1686+
ser2.iloc[0] = 100
1687+
1688+
if using_copy_on_write:
1689+
tm.assert_series_equal(ser_orig, ser)
1690+
else:
1691+
expected = Series([100, 2, 3])
1692+
tm.assert_series_equal(ser, expected)

0 commit comments

Comments
 (0)