【发布时间】:2021-02-07 18:16:51
【问题描述】:
我正在解决泰坦尼克号 kaggle 问题,我想做的一件事是使用 sklearn 的 IterativeImputer 来填充我的缺失值。
在运行插补并生成“填充”值后,我遇到了障碍。我想知道如何最好地使用填充值更新原始数据框。
代码:
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
import numpy as np
titanic = pd.DataFrame(
{
"PassengerId": [1, 2, 3, 4, 5],
"Survived": [0, 1, 1, 1, 0],
"PClass": ['3', '1', '3', '1', '3'],
"Name": ['Braund, Mr. Owen Harris', 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)',
'Heikkinen, Miss. Laina', 'Futrelle, Mrs. Jacques Heath (Lily May Peel)', 'Allen, Mr. William Henry'],
"Sex": ['male', 'female', 'female', 'female', 'male'],
"Age": [22, 38, 26, np.nan, 35],
"SibSp": [1, 1, 0, 1, 0],
"Parch": [0, 0, 0, 0, 0],
"Fare": [7.25, 71.2833, 7.925, 53.1, 8.05]
}
)
# Slicing dataframe to feed to imputer
titanic_sliced = titanic.loc[:, ['Age', 'SibSp', 'Parch', 'Fare']]
titanic_sliced.head()
切片数据集的输出:
Age SibSp Parch Fare
0 22.0 1 0 7.2500
1 38.0 1 0 71.2833
2 26.0 0 0 7.9250
3 NaN 1 0 53.1000
4 35.0 0 0 8.0500
使用随机森林估计器运行 imputer
imp = IterativeImputer(RandomForestRegressor(), max_iter=10, random_state=0)
imputed_titanic = pd.DataFrame(imp.fit_transform(titanic_sliced), columns=titanic_sliced.columns)
imputed_titanic
imputed_titanic 的输出:
Age SibSp Parch Fare
0 22.00 1.0 0.0 7.2500
1 38.00 1.0 0.0 71.2833
2 26.00 0.0 0.0 7.9250
3 36.11 1.0 0.0 53.1000
4 35.00 0.0 0.0 8.0500
所以现在我的问题是,用估算值更新原始数据框的最佳方法是什么?
【问题讨论】:
-
这不是 MRE:您发布的代码无法运行,因为您未能初始化数据框。
-
@Prune 我敢肯定你现在可能对我很生气,但再次感谢。我现在意识到我最初的要求很懒惰。实际上,我已经学到了很多东西,只是将我的问题变成了正确的格式。我运行了更新后的代码,它完全重现了我的预期。
-
就是这样:从错误中吸取教训,下次做得更好。只要您努力改进,我们很乐意与您合作。