From 79e0b5ff49f6bea87be8426ac7d155a1a54da2de Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Wed, 29 Mar 2023 10:04:53 -0400 Subject: [PATCH] Backport PR #52060: API CoW: Return read_only NumPy array from ravel --- pandas/core/series.py | 5 ++++- pandas/tests/copy_view/test_array.py | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/pandas/core/series.py b/pandas/core/series.py index 1725f754ce065..895b72decd379 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -765,7 +765,10 @@ def ravel(self, order: str = "C") -> ArrayLike: -------- numpy.ndarray.ravel : Return a flattened array. """ - return self._values.ravel(order=order) + arr = self._values.ravel(order=order) + if isinstance(arr, np.ndarray) and using_copy_on_write(): + arr.flags.writeable = False + return arr def __len__(self) -> int: """ diff --git a/pandas/tests/copy_view/test_array.py b/pandas/tests/copy_view/test_array.py index 501ef27bc291e..519479881948b 100644 --- a/pandas/tests/copy_view/test_array.py +++ b/pandas/tests/copy_view/test_array.py @@ -110,3 +110,12 @@ def test_series_to_numpy(using_copy_on_write): arr = ser.to_numpy(dtype="float64") assert not np.shares_memory(arr, get_array(ser, "name")) assert arr.flags.writeable is True + + +@pytest.mark.parametrize("order", ["F", "C"]) +def test_ravel_read_only(using_copy_on_write, order): + ser = Series([1, 2, 3]) + arr = ser.ravel(order=order) + if using_copy_on_write: + assert arr.flags.writeable is False + assert np.shares_memory(get_array(ser), arr)