{"record":{"id":"37a7ba8fb84c0742","repo":"pandas-dev/pandas","slug":"invalid-value-for-dtype-str-value-should-be-a-s","errorCode":null,"errorMessage":"Invalid value for dtype 'str'. Value should be a string or missing value (or array of those).","messagePattern":"Invalid value for dtype 'str'\\. Value should be a string or missing value \\(or array of those\\)\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/string_.py","lineNumber":863,"sourceCode":"                value = self.dtype.na_value\n            elif not isinstance(value, str):\n                raise TypeError(\n                    f\"Invalid value '{value}' for dtype '{self.dtype}'. Value should \"\n                    f\"be a string or missing value, got '{type(value).__name__}' \"\n                    \"instead.\"\n                )\n        else:\n            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:","sourceCodeStart":845,"sourceCodeEnd":881,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/string_.py#L845-L881","documentation":"Thrown by StringArray._validate_setitem_value in pandas/core/arrays/string_.py:863 when assigning a NON-SCALAR value (list, ndarray, another array) whose contents include at least one non-string, non-missing element (lib.is_string_array with skipna=True returns False). This is the array-form counterpart of error 457.","triggerScenarios":"Executing string_array[:] = [1, 2, 3] or string_array[[0,1]] = np.array([0,1]). Assigning a categorical or arrow-backed array whose values are not all strings.","commonSituations":"Bulk-replacing a string column with values from a numeric column. Assigning a list comprehension that produced ints. Setting a slice from a list with mixed types where pandas does not auto-coerce.","solutions":["Stringify the array: string_array[:] = [str(x) for x in values] or np.array([...], dtype=str).","Replace non-string entries with a missing sentinel before assignment.","Assign from another string-dtype Series/array to keep the type chain consistent."],"exampleFix":"// before\ns = pd.Series(['a','b','c'], dtype='string')\ns[:] = [1, 2, 3]  # raises TypeError\n\n// after\ns[:] = [str(x) for x in [1, 2, 3]]","handlingStrategy":"validation","validationCode":"import numpy as np, pandas as pd\ndef safe_setitem_array(arr, key, values):\n    if isinstance(getattr(arr, 'dtype', None), pd.StringDtype):\n        values = np.asarray(values, dtype=object)\n        mask = pd.isna(values)\n        values = np.array([str(v) for v in values], dtype=object)\n        values[mask] = arr.dtype.na_value\n    arr[key] = values","typeGuard":"import pandas._libs.lib as lib\ndef all_strings_or_na_array(values) -> bool:\n    import numpy as np\n    return lib.is_string_array(np.asarray(values, dtype=object), skipna=True)","tryCatchPattern":"null","preventionTips":["Stringify bulk-assigned arrays before writing into a string-dtype column.","When assigning from another column, ensure that column is also string-dtype or pre-cast.","Validate with lib.is_string_array(...) in test harnesses for string columns."],"tags":["string-array","setitem","type-check","array"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}