{"record":{"id":"2def657be00eafdc","repo":"pandas-dev/pandas","slug":"cannot-cast-nan-value-to-integer-dtype","errorCode":null,"errorMessage":"Cannot cast NaN value to Integer dtype.","messagePattern":"Cannot cast NaN value to Integer dtype\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/numeric.py","lineNumber":204,"sourceCode":"\n    if values.ndim != 1:\n        raise TypeError(\"values must be a 1D list-like\")\n\n    if mask is None:\n        if values.dtype.kind in \"iu\":\n            # fastpath\n            mask = np.zeros(len(values), dtype=np.bool_)\n        elif values.dtype.kind == \"f\":\n            # np.isnan is faster than is_numeric_na() for floats\n            # github issue: #60066\n            if is_nan_na():\n                mask = np.isnan(values)\n            else:\n                mask = np.zeros(len(values), dtype=np.bool_)\n                if dtype_cls.__name__.strip(\"_\").startswith((\"I\", \"U\")):\n                    wrong = np.isnan(values)\n                    if wrong.any():\n                        raise ValueError(\"Cannot cast NaN value to Integer dtype.\")\n        elif is_nan_na():\n            mask = libmissing.is_numeric_na(values)\n        else:\n            # is_numeric_na will raise on non-numeric NAs\n            libmissing.is_numeric_na(values)\n            mask = libmissing.is_pdna_or_none(values)\n    else:\n        assert len(mask) == len(values)\n\n    if mask.ndim != 1:\n        raise TypeError(\"mask must be a 1D list-like\")\n\n    # infer dtype if needed\n    if dtype is None:\n        dtype = default_dtype\n    else:\n        dtype = dtype.numpy_dtype\n","sourceCodeStart":186,"sourceCodeEnd":222,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/numeric.py#L186-L222","documentation":"Raised by _coerce_to_data_and_mask when constructing an integer nullable dtype (Int8/16/32/64, UInt8/16/32/64) from float data that contains NaN, but only when the is_nan_na() config option is False (the default). With default NA semantics, np.nan is NOT treated as a missing-value marker for nullable integers, so it cannot be stored in an integer column. This guard prevents silent lossy conversion of NaN into an integer slot.","triggerScenarios":"pd.array([1.0, np.nan], dtype='Int64'); df['col'] = df['col'].astype('Int64') where col is float64 containing np.nan; pd.Series([1.0, float('nan')], dtype='UInt32'). The check is gated on dtype_cls name starting with 'I' or 'U' and is_nan_na() being False.","commonSituations":"Reading float data with np.nan sentinels and trying to cast to nullable Int; mixing np.nan (float NA) with pd.NA semantics; upstream code that uses np.nan as its missing marker.","solutions":["Replace np.nan with pd.NA before casting: df['col'] = df['col'].replace({np.nan: pd.NA}).astype('Int64').","Keep the column as Float64 (which accepts np.nan/pd.NA) if integer semantics are not required.","Drop or impute the NaN rows before the integer cast: df.dropna(subset=['col']).astype('Int64').","Enable NaN-as-NA globally via pd.set_option('mode.nan_as_na', True) (changes library-wide NA semantics — use with care)."],"exampleFix":"# before\npd.array([1.0, np.nan], dtype='Int64')  # raises\n\n# after\npd.array([1.0, pd.NA], dtype='Int64')","handlingStrategy":"validation","validationCode":"import numpy as np\nimport pandas as pd\n\ndef cast_to_int_nullable(series):\n    if series.dtype.kind == 'f' and series.isna().any():\n        # np.nan isn't NA for Int dtypes by default\n        series = series.replace({np.nan: pd.NA})\n    return series.astype('Int64')","typeGuard":"def has_numpy_nan(series) -> bool:\n    import numpy as np\n    return series.dtype.kind == 'f' and bool(np.isnan(series.to_numpy()).any())","tryCatchPattern":"try:\n    s.astype('Int64')\nexcept ValueError as e:\n    if 'Cannot cast NaN' in str(e):\n        s = s.replace({np.nan: pd.NA}).astype('Int64')\n    else:\n        raise","preventionTips":["Standardize on pd.NA (not np.nan) as the missing marker for nullable-integer pipelines.","When reading float data, replace np.nan with pd.NA before casting to Int/UInt.","Keep float columns as Float64 if you need to preserve np.nan semantics."],"tags":["pandas","masked-array","numeric","nan","casting","nullable"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}