Skip to content

Commit

Permalink
Backport PR #52060 on branch 2.0.x (API CoW: Return read_only NumPy a…
Browse files Browse the repository at this point in the history
…rray from ravel) (#52273)

Backport PR #52060: API CoW: Return read_only NumPy array from ravel

Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and phofl committed Mar 29, 2023
1 parent 4c2c3f8 commit 77627e3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
5 changes: 4 additions & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,7 +772,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:
"""
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/copy_view/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 77627e3

Please sign in to comment.