简体   繁体   中英

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

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])

Take a look at pandas.Index.difference :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM