Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TST: add extra test case for np.array(obj, copy=False) read-only behaviour #60191

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2014,6 +2014,12 @@ def empty(self) -> bool:
def __array__(
self, dtype: npt.DTypeLike | None = None, copy: bool | 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(method):
ser = Series([1, 2, 3], name="name")
Expand All @@ -40,8 +46,12 @@ def test_series_values(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(method):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
Expand Down Expand Up @@ -82,7 +92,7 @@ def test_series_to_numpy():
ser.iloc[0] = 0
assert ser.values[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 @@ -130,6 +140,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():
df = DataFrame({"a": date_range("2012-01-01", periods=3)})
Expand Down