{"record":{"id":"82ff92e4acd21bb8","repo":"pandas-dev/pandas","slug":"cannot-modify-read-only-array-82ff92","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/base.py","lineNumber":569,"sourceCode":"        # *do* choose to implement __setitem__, then some semantics should be\n        # observed:\n        #\n        # * Setting multiple values : ExtensionArrays should support setting\n        #   multiple values at once, 'key' will be a sequence of integers and\n        #  'value' will be a same-length sequence.\n        #\n        # * Broadcasting : For a sequence 'key' and a scalar 'value',\n        #   each position in 'key' should be set to 'value'.\n        #\n        # * Coercion : Most users will expect basic coercion to work. For\n        #   example, a string like '2018-01-01' is coerced to a datetime\n        #   when setting on a datetime64ns array. In general, if the\n        #   __init__ method coerces that value, then so should __setitem__\n        # Note, also, that Series/DataFrame.where internally use __setitem__\n        # on a copy of the data.\n        # Check if the array is readonly\n        if self._readonly:\n            raise ValueError(\"Cannot modify read-only array\")\n\n        raise NotImplementedError(f\"{type(self)} does not implement __setitem__.\")\n\n    def __len__(self) -> int:\n        \"\"\"\n        Length of this array\n\n        Returns\n        -------\n        length : int\n        \"\"\"\n        raise AbstractMethodError(self)\n\n    def __iter__(self) -> Iterator[Any]:\n        \"\"\"\n        Iterate over elements of the array.\n        \"\"\"\n        # This needs to be implemented so that pandas recognizes extension","sourceCodeStart":551,"sourceCodeEnd":587,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/base.py#L551-L587","documentation":"Raised (ValueError) from ExtensionArray.__setitem__ when `self._readonly` is True. pandas marks arrays as read-only (sets the numpy WRITEABLE flag off and `_readonly=True`) when they are backed by memory that must not be mutated — typically zero-copy views into another array's buffer. Any in-place assignment is rejected to prevent corrupting the source buffer.","triggerScenarios":"Calling `arr[i] = value`, `arr[mask] = value`, or `Series.iloc[...] = ...` where the underlying ExtensionArray was obtained via a zero-copy operation (e.g. `.values`, `.to_numpy()` views, or array slices that share memory) that left `_readonly=True`.","commonSituations":"Mutating an array returned by `.values`/`.to_numpy()` which pandas may mark read-only to protect shared buffers; in-place edits on views produced by zero-copy constructors.","solutions":["Take a writable copy before mutating: `arr = arr.copy()`, then assign.","Operate on a fresh Series/DataFrame via normal pandas assignment rather than mutating a view extracted with `.values`.","If you must edit in place, ensure you own the buffer (construct from a copy, not a view)."],"exampleFix":"# before\nview = ser.values      # may be read-only\nview[0] = 99\n# after\narr = ser.values.copy()\narr[0] = 99","handlingStrategy":"type-guard","validationCode":"if getattr(arr, '_readonly', False):\n    raise ValueError(\"array is read-only; copy before mutating\")\narr[0] = value","typeGuard":"def is_writable(arr) -> bool:\n    return not getattr(arr, '_readonly', False)","tryCatchPattern":"try:\n    arr[0] = value\nexcept ValueError as e:\n    if \"read-only\" in str(e):\n        arr = arr.copy(); arr[0] = value\n    else:\n        raise","preventionTips":["Copy arrays returned by .values/.to_numpy() before mutating","Prefer pandas-level assignment over mutating extracted buffers"],"tags":["extension-array","read-only","setitem","copy","memory"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}