python type_error ai_generated true

ValueError: cannot convert float NaN to integer

ID: python/numpy-float-to-int-nan

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Attempting to cast a float array containing NaN into an integer dtype, which has no representation for NaN.

generic

中文

试图将包含 NaN 的浮点数组转换为整数 dtype,而整数类型无法表示 NaN。

Workarounds

  1. 95% success
    arr = np.nan_to_num(arr, nan=0.0).astype(int)
  2. 90% success
    pd.Series(arr).dropna().astype(int) or fillna(0).astype(int)

Dead Ends

Common approaches that don't work:

  1. 90% fail

    astype(int) still raises on NaN before truncation

  2. 70% fail

    Silently drops data, corrupts downstream results