Skip to content

Commit 0bbc9f5

Browse files
Backport PR #51832 on branch 2.0.x (BUG / CoW: Series.view not respecting CoW) (#51937)
Backport PR #51832: BUG / CoW: Series.view not respecting CoW Co-authored-by: Patrick Hoefler <[email protected]>
1 parent c68fd54 commit 0bbc9f5

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
@@ -221,6 +221,8 @@ Copy-on-Write improvements
221221
- Arithmetic operations that can be inplace, e.g. ``ser *= 2`` will now respect the
222222
Copy-on-Write mechanism.
223223

224+
- :meth:`Series.view` will now respect the Copy-on-Write mechanism.
225+
224226
Copy-on-Write can be enabled through one of
225227

226228
.. code-block:: python

pandas/core/series.py

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

845849
# ----------------------------------------------------------------------

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)