如何使用 scikit-learn 中的 ColumnTransformer 将多个转换应用于相同的列
How to apply multiple transforms to the same columns using ColumnTransformer in scikit-learn
我有一个如下所示的数据框:
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 pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
df = 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. ]])
我有一个如下所示的数据框:
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 pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
df = 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. ]])