{"record":{"id":"c31948fc2f491591","repo":"pandas-dev/pandas","slug":"cannot-modify-read-only-array-c31948","errorCode":null,"errorMessage":"Cannot modify read-only array","messagePattern":"Cannot modify read-only array","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":616,"sourceCode":"            if self.sp_values.dtype.kind == \"M\":\n                # However, we *do* special-case the common case of\n                # a datetime64 with pandas NaT.\n                if fill_value is NaT:\n                    # Can't put pd.NaT in a datetime64[ns]\n                    unit = np.datetime_data(self.sp_values.dtype)[0]\n                    fill_value = np.datetime64(\"NaT\", unit)  # type: ignore[call-overload]\n            try:\n                dtype = np.result_type(self.sp_values.dtype, type(fill_value))\n            except TypeError:\n                dtype = object\n\n        out = np.full(self.shape, fill_value, dtype=dtype)\n        out[self.sp_index.indices] = self.sp_values\n        return out\n\n    def __setitem__(self, key, value) -> None:\n        if self._readonly:\n            raise ValueError(\"Cannot modify read-only array\")\n        # I suppose we could allow setting of non-fill_value elements.\n        # TODO(SparseArray.__setitem__): remove special cases in\n        # ExtensionBlock.where\n        msg = \"SparseArray does not support item assignment via setitem\"\n        raise TypeError(msg)\n\n    def sort(\n        self,\n        *,\n        ascending: bool = True,\n        kind: SortKind = \"quicksort\",\n        na_position: str = \"last\",\n    ) -> None:\n        raise NotImplementedError(\"SparseArray does not support in-place sort\")\n\n    @classmethod\n    def _from_sequence(\n        cls, scalars, *, dtype: Dtype | None = None, copy: bool = False","sourceCodeStart":598,"sourceCodeEnd":634,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/array.py#L598-L634","documentation":"Raised as ValueError by SparseArray.__setitem__ when the instance is marked read-only (self._readonly is True). Even on writable instances the next line raises TypeError ('does not support item assignment via setitem'), so SparseArray item assignment is unsupported in general; the read-only guard fires first for frozen arrays.","triggerScenarios":"Calling arr[i] = value on a SparseArray exposed via .values/.to_numpy() with writeable=False; mutating a SparseArray returned from a zero-copy path that set the read-only flag.","commonSituations":"Treating SparseArray like a numpy array and trying in-place writes; reading from a memoryview-backed buffer that pandas marks read-only; libraries that freeze arrays for caching.","solutions":["Replace, don't mutate: build a new SparseArray with the modified values.","If you need mutability, materialize via np.asarray(arr) (which is writable) and rebuild a SparseArray after editing.","Use pandas Series with a sparse dtype and assign via .loc for index-aligned updates."],"exampleFix":"# before\narr[i] = new_value  # SparseArray, read-only\n# after\nvals = np.asarray(arr).copy()\nvals[i] = new_value\nnew_arr = pd.arrays.SparseArray(vals, fill_value=arr.fill_value)","handlingStrategy":"fallback","validationCode":"def sparse_array_is_writable(sparse_arr) -> bool:\n    return not getattr(sparse_arr, '_readonly', False)","typeGuard":"def writable_sparse(sparse_arr) -> bool:\n    return not bool(getattr(sparse_arr, '_readonly', False))","tryCatchPattern":"try:\n    sparse_arr[i] = value\nexcept (ValueError, TypeError):\n    vals = np.asarray(sparse_arr).copy()\n    vals[i] = value\n    sparse_arr = pd.arrays.SparseArray(vals, fill_value=sparse_arr.fill_value)","preventionTips":["Treat SparseArray as immutable; build a new one for changes.","Mutate a materialized np.ndarray and re-wrap, not the SparseArray itself.","Use Series(..., dtype='Sparse[...]') with .loc assignment for in-place-like updates."],"tags":["pandas","sparse","readonly","setitem"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}