{"record":{"id":"39acc5d84f7c073d","repo":"pandas-dev/pandas","slug":"invalid-value-value-for-dtype-self-dtype","errorCode":null,"errorMessage":"Invalid value '{value}' for dtype '{self.dtype}'. Value should be a string or missing value, got '{type(value).__name__}' instead.","messagePattern":"Invalid value '(.+?)' for dtype '(.+?)'\\. Value should be a string or missing value, got '(.+?)' instead\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/string_.py","lineNumber":755,"sourceCode":"        else:\n            # Validate that we only store NaN or strings.\n            if len(self._ndarray) and not lib.is_string_array(\n                self._ndarray, skipna=True\n            ):\n                raise ValueError(\"StringArray requires a sequence of strings or NaN\")\n            if self._ndarray.dtype != \"object\":\n                raise ValueError(\n                    \"StringArray requires a sequence of strings \"\n                    \"or NaN. Got '{self._ndarray.dtype}' dtype instead.\"\n                )\n            # TODO validate or force NA/None to NaN\n\n    def _validate_scalar(self, value):\n        # used by NDArrayBackedExtensionIndex.insert\n        if isna(value):\n            return self.dtype.na_value\n        elif not isinstance(value, str):\n            raise TypeError(\n                f\"Invalid value '{value}' for dtype '{self.dtype}'. Value should be a \"\n                f\"string or missing value, got '{type(value).__name__}' instead.\"\n            )\n        return value\n\n    @classmethod\n    def _from_sequence(\n        cls, scalars, *, dtype: Dtype | None = None, copy: bool = False\n    ) -> Self:\n        if dtype and not (isinstance(dtype, str) and dtype == \"string\"):\n            dtype = pandas_dtype(dtype)\n            assert isinstance(dtype, StringDtype) and dtype.storage == \"python\"\n        elif using_string_dtype():\n            dtype = StringDtype(storage=\"python\", na_value=np.nan)\n        else:\n            dtype = StringDtype(storage=\"python\")\n\n        from pandas.core.arrays.masked import BaseMaskedArray","sourceCodeStart":737,"sourceCodeEnd":773,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/string_.py#L737-L773","documentation":"Thrown by StringArray._validate_scalar in pandas/core/arrays/string_.py:755 — used by NDArrayBackedExtensionIndex.insert. When a scalar being inserted is not NA/NaN and not a Python str, the method rejects it because StringArray can only hold strings plus its designated missing marker. The message names the offending value, the dtype, and the actual type received.","triggerScenarios":"Calling .insert(loc, 5) on an Index backed by StringArray. Internally triggered by Index.insert / Index.append when concatenating indices that introduce a non-string scalar. Building a string index element-by-element with mixed types.","commonSituations":"Appending a numeric index level to a string index. insert() called by alignment/reindex machinery that picks up a stray int. Concatenating two differently-typed indices where pandas picks the string dtype but the other side contributes non-strings.","solutions":["Stringify the scalar before inserting: idx.insert(loc, str(5)).","Coerce missing sentinels explicitly: insert(loc, pd.NA) or insert(loc, np.nan) depending on the dtype's na_value.","If mixed types are legitimate, build the index with dtype='object' instead of 'string'."],"exampleFix":"// before\nidx = pd.Index(['a','b'], dtype='string')\nidx.insert(1, 5)  # raises TypeError\n\n// after\nidx.insert(1, '5')","handlingStrategy":"validation","validationCode":"import pandas as pd\ndef safe_insert(index_obj, loc, value):\n    if isinstance(getattr(index_obj, 'dtype', None), pd.StringDtype):\n        if not (pd.isna(value) or isinstance(value, str)):\n            value = str(value)\n    return index_obj.insert(loc, value)","typeGuard":"def is_string_scalar(v) -> bool:\n    import pandas as pd\n    return isinstance(v, str) or pd.isna(v)","tryCatchPattern":"null","preventionTips":["Stringify scalars before inserting into a string-dtype Index.","Use pd.NA (or np.nan for the NaN variant) when the intent is a missing entry.","When appending indices of different dtypes, normalize types upstream."],"tags":["string-array","index","insert","type-check"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}