{"record":{"id":"9f86da8cf1dce830","repo":"pandas-dev/pandas","slug":"invalid-value-value-s-for-dtype-self-dtype-9f86da","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/numpy_.py","lineNumber":185,"sourceCode":"\n        if copy and result is scalars:\n            result = result.copy()\n        return cls(result)\n\n    def _validate_setitem_value(self, value):\n        if isinstance(value, type(self)):\n            value = value._ndarray\n\n        # Match Block._standardize_fill_value behavior\n        if self._ndarray.dtype.kind != \"O\" and is_valid_na_for_dtype(\n            value, self._ndarray.dtype\n        ):\n            value = self.dtype.na_value\n\n        try:\n            return np_can_hold_element(self._ndarray.dtype, value)\n        except LossySetitemError as err:\n            raise TypeError(\n                f\"Invalid value '{value!s}' for dtype '{self.dtype}'\"\n            ) from err\n        except NotImplementedError:\n            # np_can_hold_element doesn't handle all dtypes (e.g. \"U\"),\n            # fall back to no validation for those.\n            return value\n\n    def searchsorted(\n        self,\n        value: NumpyValueArrayLike | ExtensionArray,\n        side: Literal[\"left\", \"right\"] = \"left\",\n        sorter: NumpySorter | None = None,\n    ) -> npt.NDArray[np.intp] | np.intp:\n        # Parent's searchsorted calls _validate_setitem_value, which is\n        # too strict for search (e.g. rejects float into int). Delegate\n        # directly to numpy which handles cross-dtype searches correctly.\n        return self._ndarray.searchsorted(value, side=side, sorter=sorter)  # type: ignore[arg-type]\n","sourceCodeStart":167,"sourceCodeEnd":203,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/numpy_.py#L167-L203","documentation":"Raised by NumpyExtensionArray._validate_setitem_value when np_can_hold_element raises LossySetitemError — i.e., assigning a value that cannot be stored losslessly in the array's dtype (for example, a float 1.5 into an int64 array, or a large int into int8). It is the per-element validation gate for __setitem__/fillna-style writes on the backing ndarray.","triggerScenarios":"Series/array __setitem__ on a NumpyExtensionArray-backed int column assigning a non-integer float; fillna with a value that does not fit the dtype; masked assignment where the rhs downcasts lossily.","commonSituations":"Filling NaN in an integer column with a float sentinel. Assigning NaN to a non-nullable integer dtype (use Int64 instead). Version upgrades where pandas tightened lossy-assignment validation.","solutions":["Use a nullable/lossless dtype: convert the column to Float64/Int64/string/object before assigning.","Pick a fill value compatible with the current dtype (e.g. 0 instead of 0.5 for int64).","Cast the array via .astype(...) to a dtype that can hold the value before assignment."],"exampleFix":"# before\ns = pd.Series([1, 2, 3], dtype='int64')\ns[s.isna()] = 1.5  # or s.iloc[0] = 1.5\n# after\ns = pd.Series([1, 2, 3], dtype='Int64')\ns.iloc[0] = 1  # integer-compatible value","handlingStrategy":"validation","validationCode":"import numpy as np\nfrom pandas.core.dtypes.cast import np_can_hold_element\nfrom pandas.errors import LossySetitemError\n\ndef can_hold(dtype, value) -> bool:\n    try:\n        np_can_hold_element(np.dtype(dtype), value)\n        return True\n    except (LossySetitemError, NotImplementedError):\n        return False","typeGuard":"import numpy as np\n\ndef value_fits_dtype(value, dtype) -> bool:\n    dt = np.dtype(dtype)\n    try:\n        np.array([value], dtype=dt)\n        return True\n    except (TypeError, ValueError, OverflowError):\n        return False","tryCatchPattern":"try:\n    arr[idx] = value\nexcept TypeError:\n    arr = arr.astype('Int64')\n    arr[idx] = value","preventionTips":["Use nullable dtypes (Int64, Float64) when you may store NA or fractional values.","Validate fill values against the column dtype before assign/fillna.","Cast columns to a wider dtype before injecting out-of-range values."],"tags":["dtype","setitem","type-coercion","pandas-arrays"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}