Skip to main content
 首页 » 编程设计

python之ValueError : Input contains NaN, 无穷大或 dtype ('float64' 的值太大)

2025年02月15日8www_RR

我正在练习贷款预测练习题并尝试填充数据中的缺失值。我从 here 获得了数据.为了完成这个问题,我正在关注这个 tutorial .

您可以在GitHub 上找到我正在使用的完整代码(文件名model.py)和数据。 .

DataFrame 看起来像这样:

最后一行执行完后(对应model.py文件中的第122行)

/home/user/.local/lib/python2.7/site-packages/numpy/lib/arraysetops.py:216: FutureWarning: numpy not_equal will not check object identity in the future. The comparison did not return the same result as suggested by the identity (`is`)) and will change. 
  flag = np.concatenate(([True], aux[1:] != aux[:-1])) 
/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20. 
  "This module will be removed in 0.20.", DeprecationWarning) 
Traceback (most recent call last): 
  File "model.py", line 123, in <module> 
    classification_model(model, df,predictor_var,outcome_var) 
  File "model.py", line 89, in classification_model 
    model.fit(data[predictors],data[outcome]) 
  File "/usr/local/lib/python2.7/dist-packages/sklearn/linear_model/logistic.py", line 1173, in fit 
    order="C") 
  File "/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py", line 521, in check_X_y 
    ensure_min_features, warn_on_dtype, estimator) 
  File "/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py", line 407, in check_array 
    _assert_all_finite(array) 
  File "/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py", line 58, in _assert_all_finite 
    " or a value too large for %r." % X.dtype) 
ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). 

由于缺少值,我收到此错误。如何填充这些缺失值?

Self_Employed 和 LoanAmount 的缺失值已填充我该如何填充其余值。谢谢您的帮助。

请您参考如下方法:

您可以使用 fillna :

df['Gender'].fillna('no data',inplace=True) 
df['Married'].fillna('no data',inplace=True) 

或者如果需要将多个列替换为相同的值:

cols = ['Gender','Married'] 
df[cols] = df[cols].fillna('no data') 

如果需要替换多个列是可能的,请使用带有列名和值的 dict 进行替换:

df = pd.DataFrame({'Gender':['m','f',np.nan],  
                   'Married':[np.nan,'yes','no'], 
                   'credit history':[1.,np.nan,0]}) 
print (df) 
  Gender Married  credit history 
0      m     NaN             1.0 
1      f     yes             NaN 
2    NaN      no             0.0 
 
d = {'Gender':'no data', 'Married':'no data', 'credit history':0} 
df = df.fillna(d) 
print (df) 
    Gender  Married  credit history 
0        m  no data             1.0 
1        f      yes             0.0 
2  no data       no             0.0