Python 如何在sklearn'中组合不同类型的缺失值;把简单的计算机合并成一个
我有两种不同类型的缺失值(np.nan和None)的数据,我试图使用SimpleComputer对它们进行插补。 虽然我可以分两步完成这项工作,但我想知道是否有办法将其合并为一个步骤。 我的代码如下:Python 如何在sklearn'中组合不同类型的缺失值;把简单的计算机合并成一个,python,pandas,numpy,scikit-learn,Python,Pandas,Numpy,Scikit Learn,我有两种不同类型的缺失值(np.nan和None)的数据,我试图使用SimpleComputer对它们进行插补。 虽然我可以分两步完成这项工作,但我想知道是否有办法将其合并为一个步骤。 我的代码如下: 将熊猫作为pd导入 将numpy作为np导入 从sklearn.impute导入SimpleImputer 列车=pd数据帧({ “用户”:[无,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy',], }) test=pd
将熊猫作为pd导入
将numpy作为np导入
从sklearn.impute导入SimpleImputer
列车=pd数据帧({
“用户”:[无,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy',],
})
test=pd.DataFrame({
“用户”:[None,np.nan,'John Smith','Mary Williams','Andy Rollins',],
})
si1=SimpleImputer(策略='常量',填充值='NAN')
si2=SimpleImputer(策略='常量',缺少值=无,填充值='缺少')
序列输入的序列interim1=si1.拟合变换(序列)
序列插补=si2.拟合变换(序列插补)
test_imputed_interim1=si1.拟合变换(test)
test_imputed=si2.拟合变换(test_imputed_interim1)
打印(“\n打印输入:”)
打印(列车输入)
打印('\ntest\u插补:')
打印(测试输入)
有没有一种方法可以将si1和si2合并为一个。我试过了
si=simplemputer(策略='constant',缺少值=[None,np.nan],填充值='missing')
但这似乎不起作用。如果要将None和np.nan值替换为'MISSING',可以使用pd.DataFrame.replace()
严格来说,用一个
单输入器无法做到这一点
一个选项,如前一个答案中所述,是使用pandas的替换
,但如果您想坚持使用scikit学习工具包,您可以使用管道
,这可能比您已有的两步解决方案更优雅:
from sklearn.pipeline import Pipeline
pipe = Pipeline([('si1',SimpleImputer(strategy='constant',fill_value='NAN')),
('si2', SimpleImputer(strategy='constant',missing_values = None, fill_value='MISSING'))])
print('\ntrain_imputed:')
print(pipe.fit_transform(train))
print('\ntest_imputed:')
print(pipe.transform(test))
这将给你同样的结果
from sklearn.pipeline import Pipeline
pipe = Pipeline([('si1',SimpleImputer(strategy='constant',fill_value='NAN')),
('si2', SimpleImputer(strategy='constant',missing_values = None, fill_value='MISSING'))])
print('\ntrain_imputed:')
print(pipe.fit_transform(train))
print('\ntest_imputed:')
print(pipe.transform(test))