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 DatetimeLikeArrayMixin.__array__ when a caller requests dtype=object together with copy=False. Converting a packed datetime/timedelta/period array to object dtype fundamentally requires materialising Python objects (a copy), so a no-copy request is impossible and pandas surfaces the conflict as ValueError rather than silently ignoring the flag.
Source
Thrown at pandas/core/arrays/datetimelike.py:349
-------
ndarray[str]
"""
raise AbstractMethodError(self)
def _formatter(self, boxed: bool = False) -> Callable[[object], str]:
# TODO: Remove Datetime & DatetimeTZ formatters.
return "'{}'".format
# ----------------------------------------------------------------
# Array-Like / EA-Interface Methods
def __array__(
self, dtype: NpDtype | None = None, copy: bool | None = None
) -> np.ndarray:
# used for Timedelta/DatetimeArray, overwritten by PeriodArray
if is_object_dtype(dtype):
if copy is False:
raise ValueError(
"Unable to avoid copy while creating an array as requested."
)
return np.array(list(self), dtype=object)
if copy is True:
return np.array(self._ndarray, dtype=dtype)
result = self._ndarray
if self._readonly:
result = result.view()
result.flags.writeable = False
return result
@overload
def __getitem__(self, key: ScalarIndexer) -> DTScalarOrNaT: ...
@overload
def __getitem__(View on GitHub (pinned to 71959b8cb9)
Solutions
- Allow the copy: drop copy=False, or pass copy=True when you need object dtype.
- Use arr.to_numpy(dtype=object) (lets pandas choose copy semantics) or arr.astype(object).
- If you truly need zero-copy, keep the native int64/datetime64 dtype instead of converting to object.
Example fix
// before
import numpy as np
arr = pd.date_range('2020', periods=3)._data
np.asarray(arr, dtype=object, copy=False) # ValueError
// after
np.asarray(arr, dtype=object) # copy permitted Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
def to_object_array(arr):
try:
return np.asarray(arr, dtype=object, copy=False)
except ValueError:
return np.asarray(arr, dtype=object) Type guard
from typing import Any
def allows_nocopy_object(arr: Any) -> bool:
# object-dtype materialisation always copies; never zero-copy
return False Try / catch
try:
np.asarray(arr, dtype=object, copy=False)
except ValueError as e:
if 'Unable to avoid copy' in str(e):
np.asarray(arr, dtype=object)
else:
raise Prevention
- Never pass copy=False with dtype=object on datetime-like arrays.
- Prefer arr.to_numpy(dtype=object) over np.asarray.
When it happens
Trigger: np.asarray(datetime_array, dtype=object, copy=False); np.array(arr, dtype=object, copy=False); or any code path that calls __array__ with both object dtype and a false copy flag. NumPy's copy=False (or the older np.array(..., copy=False)) contract triggers this.
Common situations: Downstream libraries (e.g. dask, xarray, numba interop) that pass copy=False for memory efficiency, or hand-written np.asarray(..., copy=False) calls. Also surfaces with numpy>=2.0 where __array__ gained the copy kwarg.
Related errors
- {left_base!r} is {right_base!r}
- Unable to avoid copy while creating an array as requested.
- Casting to unit-less dtype 'datetime64' is not supported. Pa
- Passing in 'datetime64' dtype with no precision is not allow
- Unable to avoid copy while creating an array as requested.
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/f7bee161e4c3b9b3.
Report an issue: GitHub.