python
type_error
ai_generated
true
ValueError:无法将浮点型 NaN 转换为整数
ValueError: cannot convert float NaN to integer
ID: python/numpy-float-to-int-nan
80%修复率
88%置信度
0证据数
2024-03-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
试图将包含 NaN 的浮点数组转换为整数 dtype,而整数类型无法表示 NaN。
English
Attempting to cast a float array containing NaN into an integer dtype, which has no representation for NaN.
解决方案
-
95% 成功率
arr = np.nan_to_num(arr, nan=0.0).astype(int)
-
90% 成功率
pd.Series(arr).dropna().astype(int) or fillna(0).astype(int)
无效尝试
常见但无效的做法:
-
90% 失败
astype(int) still raises on NaN before truncation
-
70% 失败
Silently drops data, corrupts downstream results