我有一个看起来像这样的数据框架:
df = pd.DataFrame({ 'x' : range(0,5), 'y' : [1,2,3,np.nan, np.nan]})
我想对y的值进行填补,同时对这两个变量应用标准化,代码如下:
columnPreprocess = ColumnTransformer([('imputer', SimpleImputer(strategy = 'median'), ['x','y']), ('scaler', StandardScaler(), ['x','y'])])columnPreprocess.fit_transform(df)
然而,看起来ColumnTransformer
会为每个步骤设置单独的列,不同的变换应用在不同的列上。这不是我想要的结果。
有没有办法对同一列应用不同的变换,并在输出数组中保持相同数量的列?
回答:
在这种情况下,你应该使用Pipeline
:
import pandas as pdimport numpy as npfrom sklearn.pipeline import Pipelinefrom sklearn.impute import SimpleImputerfrom sklearn.preprocessing import StandardScalerdf = pd.DataFrame({ 'x': range(0, 5), 'y': [1, 2, 3, np.nan, np.nan]})pipeline = Pipeline([ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])pipeline.fit_transform(df)# array([[-1.41421356, -1.58113883],# [-0.70710678, 0. ],# [ 0. , 1.58113883],# [ 0.70710678, 0. ],# [ 1.41421356, 0. ]])