{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/masked.py#L813-L849","documentation":"Raised by BaseMaskedArray.__array__ when called with copy=False (numpy's no-copy contract) on an array that contains missing values. A masked array cannot expose a single concrete ndarray without either filling the NAs or copying, so when hasna is True the no-copy request is impossible to honor.","triggerScenarios":"Code paths that invoke np.asarray(arr, copy=False) or any ufunc/operation requesting copy=False on a masked ExtensionArray with self._hasna True; explicit arr.__array__(copy=False).","commonSituations":"NumPy 2.0 copy=False semantics forwarded into pandas masked arrays; libraries calling np.asarray(values, copy=False) to avoid allocation; ufunc dispatch that explicitly forbids copies.","solutions":["Allow a copy: use np.asarray(arr) or arr.to_numpy() with default copy semantics.","Drop or fill NAs before the no-copy conversion: arr.dropna().__array__(copy=False).","Request object dtype explicitly when NAs must be preserved under copy=False on a no-NA subset."],"exampleFix":"// before\nnp.asarray(arr_with_na, copy=False)   # raises via __array__\n// after\nnp.asarray(arr_with_na)                # copy allowed","handlingStrategy":"validation","validationCode":"if arr._hasna:\n    out = np.asarray(arr)   # allow copy\nelse:\n    out = arr.__array__(copy=False)","typeGuard":"def supports_no_copy(arr) -> bool:\n    return not arr._hasna","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 request copy=False on arrays that may contain NAs.","Document no-copy requirements only for NA-free inputs.","Prefer arr.to_numpy() with default copy semantics for interop."],"tags":["pandas","masked-array","numpy-interop","copy","na-value"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}