如何在scikit-learn中使用ColumnTransformer对同一列应用多个变换

我有一个看起来像这样的数据框架:

df = pd.DataFrame({    'x' : range(0,5),    'y' : [1,2,3,np.nan, np.nan]})

enter image description here

我想对y的值进行填补,同时对这两个变量应用标准化,代码如下:

columnPreprocess = ColumnTransformer([('imputer', SimpleImputer(strategy = 'median'), ['x','y']),   ('scaler', StandardScaler(), ['x','y'])])columnPreprocess.fit_transform(df)

然而,看起来ColumnTransformer会为每个步骤设置单独的列,不同的变换应用在不同的列上。这不是我想要的结果。

enter image description here

有没有办法对同一列应用不同的变换,并在输出数组中保持相同数量的列?


回答:

在这种情况下,你应该使用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.        ]])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注