'Normalize only certain columns?

I am using code below to normalize columns but it tries to and starts with my label columns, is there anyway to only normalize certain columns?

x = df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df = pd.DataFrame(x_scaled)

Thanks



Solution 1:[1]

You can do

df[[col1, col2]] = scaler.fit_transform(df[[col1, col2]])

More details here: pandas dataframe columns scaling with sklearn

Solution 2:[2]

Or, if you want to scale just some columns, but don't drop the rest of the columns:

scale_cols = ['a','b']
resid_cols = df.drop(columns = scale_cols).columns
df = pd.concat([pd.DataFrame(scaler.fit_transform(df[scale_cols]),columns =scale_cols),df[resid_cols]],axis=1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexandru Placinta
Solution 2 Thanos Natsikas