Home > Mobile >  How to scale all columns except certain ones in pandas dataframe?
How to scale all columns except certain ones in pandas dataframe?

Time:11-18

With the following example code all columns are scaled with MinMaxScaler. How to change in order to only scale column A and column C? Ideally I want to do it by excluding column B by name.

import pandas as pd
from sklearn.preprocessing import MinMaxScaler


scaler = MinMaxScaler()

df = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],
                           'B':[103.02,107.26,110.35,114.23,114.68],
                           'C':[3,5,4,2,3]})

df[df.columns] = scaler.fit_transform(df[df.columns])

CodePudding user response:

Take a look at pandas.Index.difference:

scaler.fit_transform(df[df.columns.difference(['B'])])

CodePudding user response:

cols = df.columns[df.columns != 'B']
df[cols] = scaler.fit_transform(df[cols])
  • Related