{"record":{"id":"8f772f651db7dc74","repo":"pandas-dev/pandas","slug":"unable-to-avoid-copy-while-creating-an-array-as-re-8f772f","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/categorical.py","lineNumber":1786,"sourceCode":"            if dtype==None (default), the same dtype as\n            categorical.categories.dtype.\n\n        See Also\n        --------\n        numpy.asarray : Convert input to numpy.ndarray.\n\n        Examples\n        --------\n\n        >>> cat = pd.Categorical([\"a\", \"b\"], ordered=True)\n\n        The following calls ``cat.__array__``\n\n        >>> np.asarray(cat)\n        array(['a', 'b'], dtype=object)\n        \"\"\"\n        if copy is False:\n            raise ValueError(\n                \"Unable to avoid copy while creating an array as requested.\"\n            )\n\n        ret = take_nd(self.categories._values, self._codes)\n        # When we're a Categorical[ExtensionArray], like Interval,\n        # we need to ensure __array__ gets all the way to an\n        # ndarray.\n\n        # `take_nd` should already make a copy, so don't force again.\n        return np.asarray(ret, dtype=dtype)\n\n    def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):\n        # for binary ops, use our custom dunder methods\n        result = arraylike.maybe_dispatch_ufunc_to_dunder_op(\n            self, ufunc, method, *inputs, **kwargs\n        )\n        if result is not NotImplemented:\n            return result","sourceCodeStart":1768,"sourceCodeEnd":1804,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L1768-L1804","documentation":"Raised by Categorical.__array__ when called with copy=False (e.g. np.asarray(cat, copy=False)). A Categorical's materialized ndarray is always produced by gathering categories by code (take_nd), which necessarily creates a new array; there is no zero-copy path to the underlying buffer, so pandas cannot honor the no-copy request and raises rather than silently copying.","triggerScenarios":"`np.asarray(cat, copy=False)` or `np.array(cat, copy=False)` where cat is a Categorical. Also any library that passes copy=False to __array__ expecting a view.","commonSituations":"Interfacing with libraries that request zero-copy conversion for performance (e.g. some array protocols); explicitly trying to avoid allocations on hot paths.","solutions":["Allow the copy: `np.asarray(cat)` (default copy=True) or `np.array(cat)`.","If you only need codes, use `cat.codes` (a view of the int buffer, no gather).","Access categories directly via `cat.categories._values` if you want the category buffer rather than materialized values."],"exampleFix":"# before\nimport numpy as np\ncat = pd.Categorical(['a','b','a'])\nnp.asarray(cat, copy=False)\n# after\nimport numpy as np\ncat = pd.Categorical(['a','b','a'])\nnp.asarray(cat)  # allow the copy","handlingStrategy":"fallback","validationCode":"import numpy as np\n\ndef to_numpy_cat(cat, copy=True):\n    try:\n        return np.asarray(cat) if not copy else np.array(cat)\n    except ValueError:\n        return np.array(cat)","typeGuard":"def supports_no_copy(x) -> bool:\n    import pandas as pd\n    return not isinstance(getattr(x, 'dtype', None), pd.CategoricalDtype)","tryCatchPattern":"try:\n    arr = np.asarray(cat, copy=False)\nexcept ValueError as e:\n    if 'Unable to avoid copy' in str(e):\n        arr = np.asarray(cat)\n    else:\n        raise","preventionTips":["Do not pass copy=False to np.asarray on a Categorical; the gather always copies.","Use cat.codes for a no-copy view of the integer positions.","Access cat.categories._values if you need the category buffer directly."],"tags":["categorical","numpy","array-protocol","copy","valueerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}