pandas-dev/pandas · error · ValueError
Cannot cast NaN value to Integer dtype.
Error message
Cannot cast NaN value to Integer dtype.
What it means
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.
Source
Thrown at pandas/core/arrays/numeric.py:204
if values.ndim != 1:
raise TypeError("values must be a 1D list-like")
if mask is None:
if values.dtype.kind in "iu":
# fastpath
mask = np.zeros(len(values), dtype=np.bool_)
elif values.dtype.kind == "f":
# np.isnan is faster than is_numeric_na() for floats
# github issue: #60066
if is_nan_na():
mask = np.isnan(values)
else:
mask = np.zeros(len(values), dtype=np.bool_)
if dtype_cls.__name__.strip("_").startswith(("I", "U")):
wrong = np.isnan(values)
if wrong.any():
raise ValueError("Cannot cast NaN value to Integer dtype.")
elif is_nan_na():
mask = libmissing.is_numeric_na(values)
else:
# is_numeric_na will raise on non-numeric NAs
libmissing.is_numeric_na(values)
mask = libmissing.is_pdna_or_none(values)
else:
assert len(mask) == len(values)
if mask.ndim != 1:
raise TypeError("mask must be a 1D list-like")
# infer dtype if needed
if dtype is None:
dtype = default_dtype
else:
dtype = dtype.numpy_dtype
View on GitHub (pinned to 71959b8cb9)
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.
Example fix
// before pd.array([1.0, np.nan], dtype="Int64") # raises: Cannot cast NaN value to Integer dtype. // after pd.array([1.0, np.nan], dtype="Float64") # or fillna first
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
def to_int_masked_safe(vals):
arr = np.asarray(vals, dtype="float64") if np.asarray(vals).dtype.kind == "f" else np.asarray(vals)
if arr.dtype.kind == "f" and np.isnan(arr).any():
raise ValueError("float source has NaN; use Float64 or fill NaN first")
return arr Type guard
def is_int_castable_float(vals) -> bool:
import numpy as np
arr = np.asarray(vals)
return not (arr.dtype.kind == "f" and bool(np.isnan(arr).any())) Try / catch
try:
arr = pd.array(vals, dtype="Int64")
except ValueError as e:
if "Cannot cast NaN value to Integer dtype" in str(e):
arr = pd.array(vals, dtype="Float64")
else:
raise Prevention
- Use Float64 masked dtype when NaN may be present.
- Fill/drop NaN before constructing integer masked arrays.
- Centralize numeric coercion in a tested helper.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Cannot convert float NaN to integer
- cannot safely cast non-equivalent {values.dtype} to {np.dtyp
- Value must be a nonnegative integer or None
- periods must be an integer
- Converting from {self.dtype} to {dtype} is not supported. Do
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/2def657be00eafdc.
Report an issue: GitHub.