Select the numeric columns via num_cols = df.select_dtypes(include="number").columns and apply vectorized arithmetic directly—using (df[num_cols] - df[num_cols].min()) / (df[num_cols].max() - df[num_cols].min()) for Min-Max normalization into [0, 1] or (df[num_cols] - df[num_cols].mean()) / df[num_cols].std() for Z-score standardization (mean 0, std 1)—while using scikit-learn’s MinMaxScaler or StandardScaler inside machine-learning pipelines so scaling parameters fit exclusively on training data without data leakage.
Basic Example
import pandas as pd
df = pd.DataFrame({
"city": ["Lahore", "Karachi", "Islamabad", "Multan"],
"revenue": [100.0, 250.0, 400.0, 250.0],
"orders": [10, 20, 30, 20],
})
num_cols = df.select_dtypes(include="number").columns
# 1. Recommended (Min-Max scaling to [0.0, 1.0] on numeric columns only):
df_minmax = df.copy()
denom = df_minmax[num_cols].max() - df_minmax[num_cols].min()
df_minmax[num_cols] = (df_minmax[num_cols] - df_minmax[num_cols].min()).div(denom).fillna(0.0)
print(df_minmax)
# Output:
# city revenue orders
# 0 Lahore 0.0 0.0
# 1 Karachi 0.5 0.5
# 2 Islamabad 1.0 1.0
# 3 Multan 0.5 0.5
# 2. Recommended (Z-score standardization: mean = 0, std = 1):
df_zscore = df.copy()
std = df_zscore[num_cols].std(ddof=0) # ddof=0 matches sklearn StandardScaler
df_zscore[num_cols] = (df_zscore[num_cols] - df_zscore[num_cols].mean()).div(std).fillna(0.0)
print(df_zscore)
# Output:
# city revenue orders
# 0 Lahore -1.414214 -1.414214
# 1 Karachi 0.000000 0.000000
# 2 Islamabad 1.414214 1.414214
# 3 Multan 0.000000 0.000000
Key Details & Edge Cases
- Guard against constant columns (
max == minorstd == 0) producingNaN:- If every row in a numeric column has the exact same value (e.g.,
[5, 5, 5]),max - minandstdequal0, turning the entire column intoNaNon division. Chaining.fillna(0.0)(or.replace(0, 1)on the denominator) cleanly maps zero-variance columns to0.0without losing validNaNhandling when needed.
- If every row in a numeric column has the exact same value (e.g.,
- Exclude
boolor ID columns when calling.select_dtypes(include="number"):- In Pandas,
include="number"excludesboolby default, so boolean columns are safe—however, integer primary keys (user_id,zip_code) are numeric. Explicitly exclude identifier columns vianum_cols = df.select_dtypes(include="number").columns.difference(["user_id"]).
- In Pandas,
- Sample
std(ddof=1, Pandas default) vs. Populationstd(ddof=0, NumPy /StandardScalerdefault):- Pandas
Series.std()defaults toddof=1(Bessel’s correction), whereas NumPynp.std()andsklearn.preprocessing.StandardScalerdefault toddof=0. Passddof=0in Pandas if your normalized values must matchStandardScaleridentically.
- Pandas
- Prevent train/test data leakage in Machine Learning (
sklearn.preprocessing):- Never compute
.min(),.max(),.mean(), or.std()across the combined dataset beforetrain_test_split(). FitMinMaxScaler()orStandardScaler()onX_trainonly, then call.transform(X_test)(use.set_output(transform="pandas")in Scikit-Learn 1.2+ to preserve DataFrame column names and index automatically).
- Never compute
- Handling outliers with Robust Scaling (Median & IQR):
- Extreme outliers compress Min-Max values near
0and skew Z-scores. Scale using the median and interquartile range instead:q25, q75 = df[num_cols].quantile(0.25), df[num_cols].quantile(0.75) df[num_cols] = (df[num_cols] - df[num_cols].median()).div(q75 - q25).fillna(0.0)
- Extreme outliers compress Min-Max values near
Comparison of Numeric Column Normalization Methods in Pandas
| Method | Formula | Output Range / Distribution | Resistant to Outliers? | Best Used When |
|---|---|---|---|---|
Min-Max Scaling (Recommended for bounded [0, 1]) |
$\frac{x - \min(x)}{\max(x) - \min(x)}$ | [0.0, 1.0] (exact bounds) |
No (single outlier compresses all other values) | Neural networks, image/signal features, or weighted composite scores requiring fixed [0, 1] bounds. |
| Z-Score Standardization (Recommended for general stats/ML) | $\frac{x - \mu}{\sigma}$ | Mean 0.0, Std 1.0 (unbounded) |
Partial (mean and std still shift on extreme spikes) | Linear/logistic regression, PCA, SVM, clustering, and comparing features on different units. |
| Robust Scaling (Median / IQR) | $\frac{x - \text{median}(x)}{Q_{75} - Q_{25}}$ | Median 0.0, IQR 1.0 (unbounded) |
Yes | Financial, sensor, or skewed datasets containing extreme outliers. |
sklearn.preprocessing Scalers (.set_output(transform="pandas")) |
MinMaxScaler / StandardScaler / RobustScaler |
Matches chosen scaler | Depends on scaler | Supervised ML pipelines where training statistics must be saved and applied to unseen test/production data. |
You must log in or register to comment.
