Log transformation报错ValueError: cannot convert float NaN to integer如何解决
报错原因分析
- 原列存在非法对数输入值
你提前仅检查了原列无NaN,但忽略了0值、负值的情况:np.log()处理输入为0时返回-inf,处理输入为负数时返回NaN,两类结果都属于无对应整数表达的浮点类型值。 - 列数据类型不匹配
MasVnrArea列原始数据类型为整数类型(int),当你将包含NaN/-inf的浮点运算结果赋值回整数类型列时,Pandas会自动执行类型转换,由于NaN和无限值无法转为整数,因此触发该报错。
修复方案
对数转换前先对列值做偏移处理,确保所有输入值都大于0,避免生成非法值,可直接使用np.log1p()处理非负列的0值场景:
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(14,6)) # 转换前 sns.distplot(train_df['MasVnrArea'], fit=stats.norm, ax=ax[0]) ax[0].set_title('Before Normalization') # 对数转换:使用log1p等价于log(1+x),自动规避0值问题 train_df['MasVnrArea'] = np.log1p(train_df['MasVnrArea']) ax[1].set_title('After Normalization') sns.distplot(train_df['MasVnrArea'], fit=stats.norm, ax=ax[1])
内容的提问来源于stack exchange,提问作者gha7all
相关产品推荐
相关产品推荐

