{"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/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/numeric.py#L186-L222","documentation":"Raised by _coerce_to_data_and_mask when the values are floating-point, the target is an Integer masked dtype, and the float data contains NaN that cannot be represented (under the non-pandas-NA mode where np.nan is not treated as the NA sentinel). Rather than silently wrapping NaN into an invalid integer bit pattern, pandas raises.","triggerScenarios":"Constructing Int8/Int16/Int32/Int64 from a float numpy array that contains np.nan while the NA convention in use is not np.nan (is_nan_na() is False), e.g. pd.array([1.0, np.nan], dtype='Int64') in an environment configured with pd.NA as the sentinel.","commonSituations":"Mixed float source with NaN being pushed into an Integer dtype; library configuration that changed the NA sentinel behavior; data ingestion leaving NaN in numeric columns.","solutions":["Use a Floating masked dtype (Float64) to preserve NaN, then cast after handling missing values.","Drop or fill NaN before constructing: pd.array(np.nan_to_num(vals, nan=0.0), dtype='Int64').","Convert floats to the integer array via Series: pd.Series(vals).astype('Int64') after fillna."],"exampleFix":"// before\npd.array([1.0, np.nan], dtype=\"Int64\")  # raises: Cannot cast NaN value to Integer dtype.\n\n// after\npd.array([1.0, np.nan], dtype=\"Float64\")  # or fillna first","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef to_int_masked_safe(vals):\n    arr = np.asarray(vals, dtype=\"float64\") if np.asarray(vals).dtype.kind == \"f\" else np.asarray(vals)\n    if arr.dtype.kind == \"f\" and np.isnan(arr).any():\n        raise ValueError(\"float source has NaN; use Float64 or fill NaN first\")\n    return arr","typeGuard":"def is_int_castable_float(vals) -> bool:\n    import numpy as np\n    arr = np.asarray(vals)\n    return not (arr.dtype.kind == \"f\" and bool(np.isnan(arr).any()))","tryCatchPattern":"try:\n    arr = pd.array(vals, dtype=\"Int64\")\nexcept ValueError as e:\n    if \"Cannot cast NaN value to Integer dtype\" in str(e):\n        arr = pd.array(vals, dtype=\"Float64\")\n    else:\n        raise","preventionTips":["Use Float64 masked dtype when NaN may be present.","Fill/drop NaN before constructing integer masked arrays.","Centralize numeric coercion in a tested helper."],"tags":["numeric-array","integer","nan","casting"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}