Chris90
Chris90

Reputation: 1998

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

Upvotes: 0

Views: 387

Answers (2)

Thanos Natsikas
Thanos Natsikas

Reputation: 156

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)

Upvotes: 1

Alexandru Placinta
Alexandru Placinta

Reputation: 679

You can do

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

More details here: pandas dataframe columns scaling with sklearn

Upvotes: 1

Related Questions