{"record":{"id":"152e9b641e635931","repo":"pandas-dev/pandas","slug":"cannot-modify-read-only-array-152e9b","errorCode":null,"errorMessage":"Cannot modify read-only array","messagePattern":"Cannot modify read-only array","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/interval.py","lineNumber":696,"sourceCode":"            # scalar\n            if is_scalar(left) and isna(left):\n                return self._fill_value\n            return Interval(left, right, self.closed)\n        if np.ndim(left) > 1:\n            # GH#30588 multi-dimensional indexer disallowed\n            raise ValueError(\"multi-dimensional indexing not allowed\")\n        # Argument 2 to \"_simple_new\" of \"IntervalArray\" has incompatible type\n        # \"Union[Period, Timestamp, Timedelta, NaTType, DatetimeArray, TimedeltaArray,\n        # ndarray[Any, Any]]\"; expected \"Union[Union[DatetimeArray, TimedeltaArray],\n        # ndarray[Any, Any]]\"\n        result = self._simple_new(left, right, dtype=self.dtype)  # type: ignore[arg-type]\n        if getitem_returns_view(self, key):\n            result._readonly = self._readonly\n        return result\n\n    def __setitem__(self, key, value) -> None:\n        if self._readonly:\n            raise ValueError(\"Cannot modify read-only array\")\n\n        key = check_array_indexer(self, key)\n        value_left, value_right = self._validate_setitem_value(value)\n\n        self._left[key] = value_left\n        self._right[key] = value_right\n\n    def _cmp_method(self, other, op):\n        # ensure pandas array for list-like and eliminate non-interval scalars\n        if is_list_like(other):\n            if not isinstance(\n                other, (list, np.ndarray, ExtensionArray)\n            ) and not ops.has_castable_attr(other):\n                warnings.warn(\n                    f\"Operation with {type(other).__name__} is deprecated. \"\n                    \"In a future version these will be treated as scalar-like. \"\n                    \"To retain the old behavior, explicitly wrap in a Series \"\n                    \"instead.\",","sourceCodeStart":678,"sourceCodeEnd":714,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/interval.py#L678-L714","documentation":"Raised in `IntervalArray.__setitem__` when `self._readonly` is True. Some IntervalArray instances wrap a read-only memory buffer (e.g. views over a parent array, or buffers marked write-protected); any in-place assignment is refused to avoid silently failing or corrupting shared memory.","triggerScenarios":"Calling `arr[i] = value` on an IntervalArray obtained as a view (`.values` of a Series backed by a read-only buffer, or slices flagged as views); writing to an array derived from a numpy read-only array.","commonSituations":"Operating on `series.array` after the Series was constructed from a read-only numpy buffer; pickle/IPC round-trips that mark buffers read-only; cython/numba interop.","solutions":["Copy before writing: `arr = arr.copy()` then assign.","Operate at the Series level: `s.iloc[i] = value`, which handles copy semantics.","Identify the source: if the buffer is unexpectedly read-only, rebuild the array from a writable buffer."],"exampleFix":"# before\narr = df['bins'].array  # _readonly True\narr[0] = pd.Interval(0,1)\n\n# after\narr = df['bins'].array.copy()\narr[0] = pd.Interval(0,1)\ndf['bins'] = arr","handlingStrategy":"validation","validationCode":"def ensure_writable(arr):\n    if getattr(arr, '_readonly', False):\n        arr = arr.copy()\n    return arr","typeGuard":"def is_writable_interval_array(arr) -> bool:\n    return not getattr(arr, '_readonly', False)","tryCatchPattern":"try:\n    arr[i] = value\nexcept ValueError as e:\n    if 'Cannot modify read-only array' in str(e):\n        arr = arr.copy()\n        arr[i] = value\n    else:\n        raise","preventionTips":["Call .copy() before mutating arrays obtained as views from Series/DataFrames.","Prefer in-place edits at the Series level (s.iloc[i] = v).","Check the _readonly flag when interoping with numpy/cython buffers."],"tags":["interval","readonly","setitem","value-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}