{"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/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/string_.py#L737-L773","documentation":"StringArray._validate_scalar is invoked by NDArrayBackedExtensionIndex.insert (and similar scalar-insertion paths). If the value is not NA-like and not a str instance, it raises TypeError naming the value, the dtype, and the actual type received.","triggerScenarios":"Calling string_index.insert(0, 123), string_index.append(1.5), or any index operation that funnels a non-string scalar through _validate_scalar on a StringArray-backed index.","commonSituations":"Appending numeric or mixed-type values to a string-typed Index; building an index incrementally from heterogeneous data.","solutions":["Convert the value to str before inserting: str(value).","Use pd.NA (or np.nan) when you mean 'missing'.","Build the full index from a cleaned list in one step rather than inserting scalars."],"exampleFix":"// before\nidx = idx.insert(0, 123)\n\n// after\nidx = idx.insert(0, str(123))","handlingStrategy":"validation","validationCode":"value = str(value) if not (pd.isna(value) or isinstance(value, str)) else value\nidx = idx.insert(0, value)","typeGuard":"import pandas as pd\n\ndef is_string_or_na(v) -> bool:\n    return isinstance(v, str) or pd.isna(v)","tryCatchPattern":null,"preventionTips":["Convert scalars to str before inserting into a string-backed index.","Use pd.NA for missing entries rather than non-string sentinels.","Build indexes from a cleaned list in one step when possible."],"tags":["string-array","scalar","index","type-error"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}