pandas-dev/pandas · error · ValueError
Unable to avoid copy while creating an array as requested.
Error message
Unable to avoid copy while creating an array as requested.
What it means
Raised by PeriodArray.__array__ when the caller requests copy=False (numpy's no-copy contract) but the target dtype is not 'i8' (int64 ordinals). PeriodArray's natural in-memory form is int64 ordinals; any other dtype (object, bool, etc.) requires materializing a new array, so a no-copy guarantee cannot be honoured. With numpy's __array__(copy=...) protocol, copy=False means 'never copy'.
Solutions
- Allow a copy: np.asarray(period_arr, dtype=object) without copy=False, or pass copy=True.
- Request the cheap int64 view when you only need ordinals: np.asarray(period_arr, dtype='i8').
- Update callers that hard-code copy=False to pass copy=None (copy-if-needed) instead.
Example fix
# before np.asarray(period_arr, dtype=object).copy # numpy 2 may pass copy=False internally # after np.array(period_arr, dtype=object, copy=True)
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
def to_numpy_period(period_arr, dtype=None, *, allow_copy=True):
if not allow_copy and dtype not in (None, 'i8', np.int64):
raise ValueError('cannot avoid copy for non-int64 dtype')
return np.array(period_arr, dtype=dtype, copy=True if dtype not in (None, 'i8') else None) Type guard
def is_no_copy_safe_dtype(dtype) -> bool:
import numpy as np
return dtype in (None, 'i8', np.int64) Try / catch
try:
np.asarray(period_arr, dtype=target_dtype) # may pass copy=False internally on np2
except ValueError as e:
if 'avoid copy' in str(e):
np.array(period_arr, dtype=target_dtype, copy=True)
else:
raise Prevention
- Don't request copy=False for non-int64 dtypes of PeriodArray.
- For ordinal access, use dtype='i8' (the no-copy path).
- Pass copy=None (copy-if-needed) rather than copy=False in numpy 2.x interop code.
When it happens
Trigger: np.asarray(period_arr, dtype=object) when numpy passes copy=False. Internal ops that request a no-copy object/bool view. np.array(period_arr, copy=False, dtype=object) on Python 3.12+ / numpy 2.x where the copy protocol is enforced.
Common situations: numpy 2.x stricter copy semantics; downstream libraries (pyarrow, numba) that pass copy=False; explicit user request for a no-copy conversion to object dtype.
Related errors
- Unable to avoid copy while creating an array as requested.
- Cannot add or subtract timedelta64[ns] dtype from
- Cannot add/subtract timedelta-like from PeriodArray that is…
- cannot convert float NaN to integer
- Cannot return a copy of the target
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/8ce9e4350845bfbd.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/period.py:462
return None # type: ignore[return-value]
def __array__(
self, dtype: NpDtype | None = None, copy: bool | None = None
) -> np.ndarray:
if dtype == "i8":
# For NumPy 1.x compatibility we cannot use copy=None. And
# `copy=False` has the meaning of `copy=None` here:
if not copy:
result = np.asarray(self.asi8, dtype=dtype)
if self._readonly:
result = result.view()
result.flags.writeable = False
return result
else:
return np.array(self.asi8, dtype=dtype)
if copy is False:
raise ValueError(
"Unable to avoid copy while creating an array as requested."
)
if dtype == bool:
return ~self._isnan
# This will raise TypeError for non-object dtypes
return np.array(list(self), dtype=object)
def __arrow_array__(self, type=None):
"""
Convert myself into a pyarrow Array.
"""
import pyarrow
from pandas.core.arrays.arrow.extension_types import ArrowPeriodType
if type is not None:View on GitHub (pinned to 3b7651241d)