{"record":{"id":"16ec625874b9c560","repo":"pandas-dev/pandas","slug":"invalid-value-value-s-for-dtype-self-dtype-16ec62","errorCode":null,"errorMessage":"Invalid value '{value!s}' for dtype '{self.dtype}'","messagePattern":"Invalid value '(.+?)' for dtype '(.+?)'","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/masked.py","lineNumber":420,"sourceCode":"        TypeError\n        \"\"\"\n        kind = self.dtype.kind\n        # TODO: get this all from np_can_hold_element?\n        if kind == \"b\":\n            if lib.is_bool(value):\n                return value\n\n        elif kind == \"f\":\n            if lib.is_integer(value) or lib.is_float(value):\n                return value\n\n        elif lib.is_integer(value) or (lib.is_float(value) and value.is_integer()):\n            return value\n            # TODO: unsigned checks\n\n        # Note: without the \"str\" here, the f-string rendering raises in\n        #  py38 builds.\n        raise TypeError(f\"Invalid value '{value!s}' for dtype '{self.dtype}'\")\n\n    def insert(self, loc: int, item) -> Self:\n        if not is_valid_na_for_dtype(item, self.dtype):\n            self._validate_setitem_value(item)\n        return super().insert(loc, item)\n\n    def _validate_listlike(self, value) -> tuple[np.ndarray, npt.NDArray[np.bool_]]:\n        \"\"\"\n        Validate a non-scalar setitem value and return ``(data, mask)``.\n\n        Raises\n        ------\n        TypeError\n            If `value` cannot be losslessly stored in self.dtype.\n        \"\"\"\n        kind = self.dtype.kind\n\n        if hasattr(value, \"dtype\"):","sourceCodeStart":402,"sourceCodeEnd":438,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/masked.py#L402-L438","documentation":"Raised by BaseMaskedArray._validate_setitem_value when a scalar cannot be losslessly stored in the array's dtype. The method short-circuits to a TypeError when the value's kind is incompatible: e.g. a string into Int64, a float-with-fraction into Int64, a non-bool into Boolean, or a NaN where not allowed. The check protects the underlying numpy buffer from silent truncation.","triggerScenarios":"Setting arr[i] = 'x' on an Int64 array, arr[i] = 1.5 on an Int64 array, arr[i] = 1 on a Boolean array, or any scalar whose kind doesn't match the masked array's dtype.kind.","commonSituations":"User input parsed as strings reaching numeric columns, mixed-type CSV data, conditional assignments where the value's type wasn't coerced.","solutions":["Cast the value before assigning: int(value), float(value), bool(value) as appropriate to arr.dtype.kind.","Use pd.NA for missing values instead of 'nan' strings or None-with-type-mismatch.","If you need heterogeneous values, switch the column dtype to object or string."],"exampleFix":"# before\narr = pd.array([1, 2, 3], dtype='Int64')\narr[0] = '5'\n\n# after\narr[0] = int('5')","handlingStrategy":"type-guard","validationCode":"def coerce_scalar(arr, value):\n    kind = arr.dtype.kind\n    if kind == 'b':\n        return bool(value)\n    if kind in 'iu':\n        return int(value)\n    if kind == 'f':\n        return float(value)\n    return value","typeGuard":"def scalar_matches_dtype(arr, value) -> bool:\n    kind = arr.dtype.kind\n    if kind == 'b':\n        return isinstance(value, bool)\n    if kind in 'iu':\n        return isinstance(value, int) and not isinstance(value, bool)\n    if kind == 'f':\n        return isinstance(value, (int, float)) and not isinstance(value, bool)\n    return False","tryCatchPattern":"try:\n    arr[i] = value\nexcept TypeError as e:\n    if 'Invalid value' in str(e):\n        arr[i] = coerce_scalar(arr, value)","preventionTips":["Coerce scalar values to the column dtype before assignment.","Use pd.NA rather than strings or None for missing values.","Add dtype-aware input validation at API boundaries."],"tags":["masked-array","dtype","setitem","type-error"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}