{"record":{"id":"8ce9e4350845bfbd","repo":"pandas-dev/pandas","slug":"unable-to-avoid-copy-while-creating-an-array-as-re-8ce9e4","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/period.py","lineNumber":462,"sourceCode":"            return None  # type: ignore[return-value]\n\n    def __array__(\n        self, dtype: NpDtype | None = None, copy: bool | None = None\n    ) -> np.ndarray:\n        if dtype == \"i8\":\n            # For NumPy 1.x compatibility we cannot use copy=None.  And\n            # `copy=False` has the meaning of `copy=None` here:\n            if not copy:\n                result = np.asarray(self.asi8, dtype=dtype)\n                if self._readonly:\n                    result = result.view()\n                    result.flags.writeable = False\n                return result\n            else:\n                return np.array(self.asi8, dtype=dtype)\n\n        if copy is False:\n            raise ValueError(\n                \"Unable to avoid copy while creating an array as requested.\"\n            )\n\n        if dtype == bool:\n            return ~self._isnan\n\n        # This will raise TypeError for non-object dtypes\n        return np.array(list(self), dtype=object)\n\n    def __arrow_array__(self, type=None):\n        \"\"\"\n        Convert myself into a pyarrow Array.\n        \"\"\"\n        import pyarrow\n\n        from pandas.core.arrays.arrow.extension_types import ArrowPeriodType\n\n        if type is not None:","sourceCodeStart":444,"sourceCodeEnd":480,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/period.py#L444-L480","documentation":"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'.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"# before\nnp.asarray(period_arr, dtype=object).copy  # numpy 2 may pass copy=False internally\n\n# after\nnp.array(period_arr, dtype=object, copy=True)","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef to_numpy_period(period_arr, dtype=None, *, allow_copy=True):\n    if not allow_copy and dtype not in (None, 'i8', np.int64):\n        raise ValueError('cannot avoid copy for non-int64 dtype')\n    return np.array(period_arr, dtype=dtype, copy=True if dtype not in (None, 'i8') else None)","typeGuard":"def is_no_copy_safe_dtype(dtype) -> bool:\n    import numpy as np\n    return dtype in (None, 'i8', np.int64)","tryCatchPattern":"try:\n    np.asarray(period_arr, dtype=target_dtype)  # may pass copy=False internally on np2\nexcept ValueError as e:\n    if 'avoid copy' in str(e):\n        np.array(period_arr, dtype=target_dtype, copy=True)\n    else:\n        raise","preventionTips":["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."],"tags":["pandas","period","numpy-interop","copy","numpy2"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}