{"record":{"id":"fe600447218b8341","repo":"pandas-dev/pandas","slug":"unable-to-avoid-copy-while-creating-an-array-as-re-fe6004","errorCode":null,"errorMessage":"Unable to avoid copy while creating an array as requested.","messagePattern":"Unable to avoid copy while creating an array as requested\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/masked.py","lineNumber":831,"sourceCode":"    __array_priority__ = 1000  # higher than ndarray so ops dispatch to us\n\n    def __array__(\n        self, dtype: NpDtype | None = None, copy: bool | None = None\n    ) -> np.ndarray:\n        \"\"\"\n        the array interface, return my values\n        We return an object array here to preserve our scalar values\n        \"\"\"\n        if copy is False:\n            if not self._hasna:\n                # special case, here we can simply return the underlying data\n                result = np.array(self._data, dtype=dtype, copy=copy)\n                # If the ExtensionArray is readonly, make the numpy array readonly too\n                if self._readonly:\n                    result = result.view()\n                    result.flags.writeable = False\n                return result\n            raise ValueError(\n                \"Unable to avoid copy while creating an array as requested.\"\n            )\n\n        if copy is None:\n            copy = False  # The NumPy copy=False meaning is different here.\n        return self.to_numpy(dtype=dtype, copy=copy)\n\n    _HANDLED_TYPES: tuple[type, ...]\n\n    def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):\n        # For MaskedArray inputs, we apply the ufunc to ._data\n        # and mask the result.\n\n        out = kwargs.get(\"out\", ())\n\n        for x in inputs + out:\n            if not isinstance(x, (*self._HANDLED_TYPES, BaseMaskedArray)):\n                return NotImplemented","sourceCodeStart":813,"sourceCodeEnd":849,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/masked.py#L813-L849","documentation":"Raised by BaseMaskedArray.__array__ when NumPy (or user code) requests copy=False but the array has missing values. With NAs present pandas must materialize a copy to substitute the na_value into the masked positions, so it cannot honor a zero-copy request and raises rather than silently copying.","triggerScenarios":"Calling np.asarray(arr, dtype=...) with copy=False semantics (NumPy 2.0 copy keyword), or any code path that invokes __array__(copy=False) on a masked array that has NAs (self._hasna True). Also triggered by libraries that pass copy=False unconditionally.","commonSituations":"NumPy 2.0 introduced the copy keyword on np.asarray; downstream libraries passing copy=False to avoid copies; passing a nullable Series/array into a function asserting no-copy.","solutions":["Allow a copy: call np.asarray(arr) without copy=False, or pass copy=True.","Strip NAs before the no-copy conversion if you truly need a view: arr = arr[~arr.isna()] then arr.to_numpy(copy=False) on the underlying data.","Use arr.to_numpy(dtype=..., na_value=...) explicitly which accepts the necessary copy."],"exampleFix":"// before\nnp.asarray(nullable_arr, copy=False)  # raises if arr has NA\n\n// after\nnp.asarray(nullable_arr)  # allow copy","handlingStrategy":"validation","validationCode":"def no_copy_numpy(arr, dtype=None):\n    if getattr(arr, \"_hasna\", False):\n        raise ValueError(\"cannot avoid copy when array has NA\")\n    return np.asarray(arr, dtype=dtype)  # copy allowed/none","typeGuard":"def can_zero_copy_to_numpy(arr) -> bool:\n    return not getattr(arr, \"_hasna\", False)","tryCatchPattern":"try:\n    out = np.asarray(arr, copy=False)\nexcept ValueError as e:\n    if \"Unable to avoid copy\" in str(e):\n        out = np.asarray(arr)\n    else:\n        raise","preventionTips":["Do not pass copy=False to np.asarray on nullable arrays.","Drop NAs first if a true zero-copy view is required.","Pin behavior via arr.to_numpy(copy=...) which documents copy semantics."],"tags":["masked-array","numpy-interop","copy","missing-values"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}