{"record":{"id":"5d02ab71742ccb47","repo":"pandas-dev/pandas","slug":"cannot-modify-read-only-array-5d02ab","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/string_.py","lineNumber":871,"sourceCode":"            value = extract_array(value, extract_numpy=True)\n            if not is_array_like_deprecate_non_pandas(value):\n                value = np.asarray(value, dtype=object)\n            elif isinstance(value.dtype, type(self.dtype)):\n                return value\n            else:\n                # cast categories and friends to arrays to see if values are\n                # compatible, compatibility with arrow backed strings\n                value = np.asarray(value)\n            if len(value) and not lib.is_string_array(value, skipna=True):\n                raise TypeError(\n                    \"Invalid value for dtype 'str'. Value should be a \"\n                    \"string or missing value (or array of those).\"\n                )\n        return value\n\n    def __setitem__(self, key, value) -> None:\n        if self._readonly:\n            raise ValueError(\"Cannot modify read-only array\")\n\n        value = self._validate_setitem_value(value)\n\n        key = check_array_indexer(self, key)\n        scalar_key = lib.is_scalar(key)\n        scalar_value = lib.is_scalar(value)\n        if scalar_key and not scalar_value:\n            raise ValueError(\"setting an array element with a sequence.\")\n\n        if not scalar_value:\n            if value.dtype == self.dtype:\n                value = value._ndarray\n            else:\n                value = np.asarray(value)\n                mask = isna(value)\n                if mask.any():\n                    value = value.copy()\n                    value[isna(value)] = self.dtype.na_value","sourceCodeStart":853,"sourceCodeEnd":889,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/string_.py#L853-L889","documentation":"Thrown by StringArray.__setitem__ in pandas/core/arrays/string_.py:871 when the array's _readonly flag is True. The flag (defined as a class attribute on ExtensionArray, default False) is set to True on arrays produced by view-preserving operations (certain slices, astype-is-view results) to prevent mutating shared backing memory. Any attempted mutation raises ValueError before the value is even validated.","triggerScenarios":"Calling .iloc[i] = ... on a StringArray obtained from a no-copy slice (e.g., head(), a boolean mask that returned a view, or astype between compatible dtypes). Mutating an array surfaced by .values or .array on a Series that shares memory with another object. Writing to an array after .astype('string') on a parent that flagged the result read-only.","commonSituations":"Chained indexing patterns that return views. Arrow-backed or masked arrays propagated _readonly through copy=False paths. Code that previously mutated object-dtype slices freely now failing after migrating to 'string' dtype.","solutions":["Take a writable copy before mutating: writable = string_array.copy(); writable[i] = value.","Use Series-level assignment which copies as needed: series.loc[i] = value.","Avoid mutating arrays obtained from .values / .array directly; rebuild via pd.array(...)."],"exampleFix":"// before\ns = pd.Series(['a','b'], dtype='string')\nv = s.values[:]\nv[0] = 'z'  # may raise ValueError if _readonly\n\n// after\nwritable = s.values.copy()\nwritable[0] = 'z'","handlingStrategy":"validation","validationCode":"import pandas as pd\ndef writable_string_array(arr):\n    if getattr(arr, '_readonly', False):\n        arr = arr.copy()\n    return arr","typeGuard":"def is_readonly(arr) -> bool:\n    return bool(getattr(arr, '_readonly', False))","tryCatchPattern":"null","preventionTips":["Call .copy() before mutating arrays obtained from slices, .values, or astype.","Prefer Series-level assignment (.loc, .iloc) which handles copy semantics.","Treat _readonly arrays as immutable views; rebuild rather than mutate."],"tags":["string-array","readonly","setitem","copy"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}