def fill_missing_rf(X,y,to_fill):
"""
使用随机森林填补一个特征缺失值的函数
X 当然是包含所有特征的矩阵
y 就是用0和1组成的表示客户逾期还是不逾期
to_fill 需要填补的这一列的 【名称】
“""
df = X.copy()
#就是后面的Y
fill = df.loc[:,to_fill]
#重组的X矩阵
df = pd.concat([df.loc[:,df.columns !=to_fill],pd.DataFrame(y)],axis=1)
#提炼出训练集和测试集
#巧在用了Y的索引来确定X
Ytrain = fill[fill.notnull()]
Ytest = fill[fill.isnull()]
Xtrain = df.iloc[Ytrain.index,:]
Xtest = df.iloc[Ytest.index,:]
#填补数据
from sklearn.ensemble import RandomForestRegressor as rfr
rfr = rfr(n_estimators=100)
rfr = rfr.fit(Xtrain,Ytrain)
Ypredict = rdr.predict(Xtest)
return Ypredict
X =data.loc[:,1:]
y = data.loc["SeriousDlqin2yrs"]
Ypredict = fill_missing_rf(X,y,,"MonthlyIncome")
#取出这一列为空的所有值/1 判定是否为空,2
data.loc[data.loc[:,"MonthlyIncome"].isnull(),"MonthlyIncome"] = Ypredict