Skip to content

Commit f1e7115

Browse files
fix remaining case for DataFrame raising an error if copy could not be avoided
1 parent f895034 commit f1e7115

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

pandas/core/generic.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2014,6 +2014,12 @@ def empty(self) -> bool:
20142014
def __array__(
20152015
self, dtype: npt.DTypeLike | None = None, copy: bool | None = None
20162016
) -> np.ndarray:
2017+
if copy is False and not self._mgr.is_single_block and not self.empty:
2018+
# check this manually, otherwise ._values will already return a copy
2019+
# and np.array(values, copy=False) will not raise an error
2020+
raise ValueError(
2021+
"Unable to avoid copy while creating an array as requested."
2022+
)
20172023
values = self._values
20182024
if copy is None:
20192025
# Note: branch avoids `copy=None` for NumPy 1.x support

pandas/tests/copy_view/test_array.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,9 @@ def test_dataframe_multiple_numpy_dtypes():
138138
assert not np.shares_memory(arr, get_array(df, "a"))
139139
assert arr.flags.writeable is True
140140

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

142145
def test_values_is_ea():
143146
df = DataFrame({"a": date_range("2012-01-01", periods=3)})

0 commit comments

Comments
 (0)