Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to Normalize Data in Python with StandardScaler and MinM

How to Normalize Data in Python with StandardScaler and MinMaxScaler

Normalizing data in Python means putting numeric variables on a comparable scale before you train a model. The two common choices are StandardScaler, which centers each column at mean 0 and scales it to standard deviation 1, and MinMaxScaler, which compresses values into a fixed range, usually 0 to 1. The choice matters most in algorithms that measure distance or optimize by gradient.

Topics: standardscaler, normalização, pré-processamento

Why does variable scale change model results?

When one column is measured in thousands and another is a percentage, the larger numbers dominate any calculation that uses distance. A distance-based algorithm reads that magnitude as importance, even if the variable carries less information about the problem. Normalization removes that accidental advantage.

Gradient-based methods also care about scale. Variables in different orders of magnitude make the error surface stretched, so training can be slower and more sensitive to the learning rate. Scaling puts columns in the same order of magnitude and gives the optimizer a more regular space.

Not every model needs it. Trees and tree ensembles split one variable at a time, so they are largely indifferent to scale.

How do you apply StandardScaler in Python step by step?

StandardScaler turns each value into a z-score: it subtracts the column mean and divides by the standard deviation. The fitted result has mean 0 and standard deviation 1. Fit it on training data only.

from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test)

The rule is fit_transform on training data and transform on test data and future production data. If you fit the scaler on the full dataset, the mean and standard deviation carry information from the test set. That is data leakage, and the final metric becomes too optimistic.

fit_transform returns a NumPy array. To keep column names in a DataFrame, rebuild it with pd.DataFrame(scaler.fit_transform(X_train), columns=X_train.columns, index=X_train.index). In a scikit-learn Pipeline, the scaler is a step and the fit stays inside training folds automatically.

How do you use MinMaxScaler and when is it the right choice?

MinMaxScaler applies a linear transformation that maps the minimum to 0 and the maximum to 1 by default, controlled by feature_range. It does not center on the mean or divide by standard deviation; it compresses the original amplitude.

from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0, 1)) X_train_minmax = scaler.fit_transform(X_train) X_test_minmax = scaler.transform(X_test)

The advantage appears when the data has known limits and preserving that range is useful, such as image pixels or measurements with a defined scale. The drawback is sensitivity to outliers: one extreme value compresses the rest of the column into a narrow band and information is lost.

If outliers are meaningful, compare with RobustScaler, which uses the median and interquartile range. The decision depends on the variable distribution and the algorithm, not on style.

StandardScaler or MinMaxScaler: which should you choose?

A good rule is to start with StandardScaler for distance-based and gradient-based models, then test MinMaxScaler when a fixed range is required and extreme values are not a problem. Inspect histograms and boxplots before deciding. A long-tailed variable often gets squeezed by MinMaxScaler; for a distance-based model, standardization is usually the safer first test.

The table below summarizes the objective differences between the two scalers.

How do you avoid data leakage when normalizing?

Data leakage is the most common normalization error. It happens when the scaler is fitted before the train/test split, or when the same fitted object is reused incorrectly across folds. The mean, standard deviation, minimum, and maximum must come from training data only.

The clean pattern is to split first, fit the scaler on X_train, transform X_train and X_test with that fitted scaler, and keep the object for production. With cross-validation, put the scaler inside a Pipeline so each fold fits its own transformation. Otherwise, validation scores can look better than the model will perform on new data.

Also check the order of operations. Fit the scaler after handling missing values and before the model. If you add new numeric columns later, refit the preprocessing pipeline on training data and re-run validation. Do not fit on the test set to make the ranges match; that defeats the purpose of the holdout.

Where can you practice normalization with real projects?

If you want to practice these steps on real data, the Python for Data Science and Analytics course is a from-zero-to-advanced program with three main modules—Basic, Intermediate, and Advanced—plus bonus modules. It covers IDE and Jupyter Notebook setup, NumPy and Pandas, user-defined functions, loops and conditionals, data visualization, data cleaning and preparation, and outlier detection.

The machine learning modules cover linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation. The course ends with a final project: end-to-end exploratory analysis and machine learning.

Lessons are recorded in high quality and can be watched at your own pace. The course includes guided exercises, real market projects for a portfolio, unlimited access with no expiration date, a completion certificate, and an exclusive community for networking. Payment goes through Hotmart checkout with card or boleto, and you do not need prior programming experience to start. The course site is python.paanalytics.net.

CriterionStandardScalerMinMaxScaler
OutputMean 0, standard deviation 1Fixed range, default 0 to 1
CenterSubtracts the column meanUses minimum and maximum
Sensitivity to outliersCan be affected by extreme valuesStrongly affected; one outlier compresses the rest
Good fitDistance-based and gradient-based modelsKnown ranges with no strong outliers
Typical examplesK-Means, SVM, KNN, PCA, regularized regressionImage pixels, bounded measurements
Fit ruleFit on training data onlyFit on training data only

Based on scikit-learn preprocessing behavior described in this tutorial.

Explore the Python for Data Science and Analytics course

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Do I need to normalize every feature?

No. Trees and tree-based ensembles are usually indifferent to scale. Scaling matters most for distance-based models, PCA, regularized regression, and neural models.

Should I normalize before or after splitting the data?

After splitting. Fit the scaler on training data only, then transform test data with the same fitted scaler. Fitting before the split leaks test information.

What is the difference between normalization and standardization?

In this context, standardization usually means StandardScaler (mean 0, standard deviation 1). Normalization with MinMaxScaler maps values to a fixed range. Both are scalers, and the names are often used loosely.

Can MinMaxScaler handle outliers?

It is highly sensitive to outliers because the minimum and maximum set the range. One extreme value can compress the rest of the column. If outliers matter, compare with RobustScaler.

Does scaling change the interpretation of coefficients?

Yes. Standardized coefficients are expressed in standard-deviation units, so they are not on the original measurement scale. For reporting, inverse_transform can bring predictions back to the original scale, and coefficients need to be explained accordingly.

Ler em português →