{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/masked.py#L402-L438","documentation":"Raised by BaseMaskedArray._validate_setitem_value when a scalar value cannot be losslessly stored in the array's dtype. Integer masked arrays accept integers or integer-valued floats, float arrays accept any integer or float, and boolean arrays accept only bools; anything else (strings, non-integer floats into Int dtypes, None) is rejected to avoid silent coercion.","triggerScenarios":"Assigning arr[i] = value, arr.fillna(value), arr.insert(loc, item), or any setitem path where value is a scalar that fails the kind checks in _validate_setitem_value (e.g. arr[i] = 1.5 on an Int64 array, or arr[i] = 'x' on any numeric masked array).","commonSituations":"Mixing dtypes after refactoring a column from float to Int; loading CSV data typed as object then assigning string cells into a nullable Int column; passing user input without normalization; bugs where a column is typed Int64 but the upstream producer emits floats.","solutions":["Convert the value to the array's native type before assignment (int(value), float(value), bool(value)).","Change the array's dtype to one that can hold the value, e.g. arr = arr.astype('Float64').","Sanitize incoming data so only values valid for self.dtype reach the setitem path."],"exampleFix":"// before\narr = pd.array([1, 2, 3], dtype='Int64')\narr[0] = 1.5   # raises: 1.5 is not integer-valued\n// after\narr = arr.astype('Float64')\narr[0] = 1.5","handlingStrategy":"validation","validationCode":"def coerce_to_dtype(dtype, value):\n    kind = dtype.kind\n    if kind == 'b':\n        return bool(value)\n    if kind == 'f':\n        return float(value)\n    if value is not None and (isinstance(value, float) and not float(value).is_integer()):\n        raise ValueError(f'{value!r} not losslessly storable in {dtype}')\n    return int(value)\n\narr[i] = coerce_to_dtype(arr.dtype, value)","typeGuard":"def is_valid_for_dtype(dtype, value) -> bool:\n    import numpy as np\n    k = dtype.kind\n    if k == 'b':\n        return isinstance(value, (bool, np.bool_))\n    if k == 'f':\n        return isinstance(value, (int, float, np.integer, np.floating)) and not isinstance(value, bool)\n    if k in 'iu':\n        return isinstance(value, (int, np.integer)) or (isinstance(value, float) and value.is_integer())\n    return False","tryCatchPattern":"try:\n    arr[i] = value\nexcept TypeError as e:\n    if 'Invalid value' in str(e):\n        arr = arr.astype('Float64')\n        arr[i] = value\n    else:\n        raise","preventionTips":["Normalize incoming scalars to the column dtype before assignment.","When upgrading an Int column to hold fractional values, astype('Float64') first.","Validate user-supplied values against arr.dtype.kind in input layers."],"tags":["pandas","masked-array","dtype","setitem","type-coercion"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}