Skip to content

Commit

Permalink
Backport PR pandas-dev#60191: TST: add extra test case for np.array(o…
Browse files Browse the repository at this point in the history
…bj, copy=False) read-only behaviour
  • Loading branch information
jorisvandenbossche authored and meeseeksmachine committed Nov 7, 2024
1 parent b5d0615 commit ae81b62
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
6 changes: 6 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2149,6 +2149,12 @@ def empty(self) -> bool_t:
def __array__(
self, dtype: npt.DTypeLike | None = None, copy: bool_t | None = None
) -> np.ndarray:
if copy is False and not self._mgr.is_single_block and not self.empty:
# check this manually, otherwise ._values will already return a copy
# and np.array(values, copy=False) will not raise an error
raise ValueError(
"Unable to avoid copy while creating an array as requested."
)
values = self._values
if copy is None:
# Note: branch avoids `copy=None` for NumPy 1.x support
Expand Down
37 changes: 32 additions & 5 deletions pandas/tests/copy_view/test_array.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import numpy as np
import pytest

from pandas.compat.numpy import np_version_gt2

from pandas import (
DataFrame,
Series,
Expand All @@ -15,8 +17,12 @@

@pytest.mark.parametrize(
"method",
[lambda ser: ser.values, lambda ser: np.asarray(ser)],
ids=["values", "asarray"],
[
lambda ser: ser.values,
lambda ser: np.asarray(ser),
lambda ser: np.array(ser, copy=False),
],
ids=["values", "asarray", "array"],
)
def test_series_values(using_copy_on_write, method):
ser = Series([1, 2, 3], name="name")
Expand Down Expand Up @@ -45,8 +51,12 @@ def test_series_values(using_copy_on_write, method):

@pytest.mark.parametrize(
"method",
[lambda df: df.values, lambda df: np.asarray(df)],
ids=["values", "asarray"],
[
lambda df: df.values,
lambda df: np.asarray(df),
lambda ser: np.array(ser, copy=False),
],
ids=["values", "asarray", "array"],
)
def test_dataframe_values(using_copy_on_write, using_array_manager, method):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
Expand Down Expand Up @@ -100,7 +110,7 @@ def test_series_to_numpy(using_copy_on_write):
arr[0] = 0
assert ser.iloc[0] == 0

# specify copy=False gives a writeable array
# specify copy=True gives a writeable array
ser = Series([1, 2, 3], name="name")
arr = ser.to_numpy(copy=True)
assert not np.shares_memory(arr, get_array(ser, "name"))
Expand Down Expand Up @@ -174,6 +184,23 @@ def test_dataframe_multiple_numpy_dtypes():
assert not np.shares_memory(arr, get_array(df, "a"))
assert arr.flags.writeable is True

if np_version_gt2:
# copy=False semantics are only supported in NumPy>=2.

with pytest.raises(ValueError, match="Unable to avoid copy while creating"):
arr = np.array(df, copy=False)

arr = np.array(df, copy=True)
assert arr.flags.writeable is True


def test_dataframe_single_block_copy_true():
# the copy=False/None cases are tested above in test_dataframe_values
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
arr = np.array(df, copy=True)
assert not np.shares_memory(arr, get_array(df, "a"))
assert arr.flags.writeable is True


def test_values_is_ea(using_copy_on_write):
df = DataFrame({"a": date_range("2012-01-01", periods=3)})
Expand Down

0 comments on commit ae81b62

Please sign in to comment.