How to apply scaling to selected features, when using scaling in a pipeline?

Viewed 258

I have the following dataset(showing only first-five rows here):

     x0_Open Play   x1_Foot x1_Head  distance     angle
0        1             1       0     26.213579  14.213353
1        1             1       0     17.011103  20.424801
2        1             1       0     24.033554  13.163370
3        1             1       0     18.165922  21.541146
4        1             1       0     24.563994  16.868598

Here, the first three features are the result of OneHotEncoder. And now I want to scale the distance and angle using StandardScaler.

The general structure to code a pipeline in Python is as follows:

from sklearn.pipeline import make_pipeline

scaled_log_reg = make_pipeline(StandardScaler(), LogisticRegression())

But this will scale the entire dataset, I just want to scale down distance and angle features. How can I implement this concept of performing scaling to particular features when applying scaling in a pipeline.

2 Answers

You can use ColumnTransformer:

scaler = ColumnTransformer([('scaler (or any name)', 
                              StandardScaler(),
                             ['distance', 'angle']
                            )], remainder='passthrough')
  • two features features = ['distance','angle']

  • X = dataframe[features]

when you do StandardScaler().fit at that time provide this two parameters features like this StandardScaler().fit(X)

hope this will help ;)

Related