Feature Engineering Cheat Sheet β€” Encoding Β· Scaling Β· Imputation Β· Selection Β· PCA | Dataplexa
← Back to Cheat Sheets
Sheet icon

Feature Engineering Cheat Sheet

Encoding Β· Scaling Β· Imputation Β· Feature Creation Β· Selection Β· Dimensionality Reduction Β· Pipelines

Sheet 4 of 4 Machine Learning Intermediate Printable

Feature Engineering β€” Overview

Foundation
Core Idea
Better features β†’ better model, always
A simple model with great features beats a complex model with raw data
StepTask
1. UnderstandExplore data β€” distributions, types, missing, correlations
2. CleanHandle missing values, outliers, duplicates, wrong types
3. EncodeConvert categoricals to numbers the model understands
4. ScaleNormalise / standardise numerical features
5. CreateDerive new features from existing ones
6. SelectRemove irrelevant / redundant features
7. ReduceCompress feature space (PCA, t-SNE)
Feature TypeExamplesActions
Numericalage, price, countScale, bin, log-transform, clip
Categoricalcity, color, brandOne-hot, ordinal, target encode
Ordinalrating, education levelOrdinal encode, keep order
Datetimetimestamp, dateExtract hour, day, month, week, cyclic encode
Textreviews, descriptionsTF-IDF, word embeddings, n-grams
Booleanis_active, has_promoKeep as 0/1 directly
High-cardinalityZIP code, user_idTarget encode, frequency encode, hash
AlgorithmNeeds Scaling?Needs Encoding?
Linear / Logistic Regβœ… Yesβœ… Yes
SVMβœ… Yesβœ… Yes
KNNβœ… Yesβœ… Yes
Neural Networksβœ… Yesβœ… Yes
Decision Tree❌ Noβœ… Yes
Random Forest❌ Noβœ… Yes
XGBoost / LGBM❌ No⚠ Often built-in
Naive Bayes❌ Noβœ… Yes
Rule: Distance-based and gradient-based algorithms need scaling. Tree-based algorithms generally don't.

Encoding Categorical Variables

Encoding
MethodWhen to UseCreates
One-HotNominal, low cardinality (<20 cats)Binary columns per category
OrdinalOrdered categories (low/mid/high)Single integer column
LabelTree models only β€” no order impliedSingle integer column
TargetHigh cardinality, regression/classificationMean target per category
FrequencyHigh cardinality, quick baselineCategory count/frequency
BinaryVery high cardinality, memory-efficientBinary bit columns
HashingExtremely high cardinality, NLPFixed-size hash vector
sklearn Encoding
from sklearn.preprocessing import (
  OneHotEncoder, OrdinalEncoder, LabelEncoder)

# One-Hot β€” drop first to avoid dummy trap
OneHotEncoder(drop='first', sparse_output=False)

# Ordinal β€” specify order explicitly
OrdinalEncoder(categories=[['low','mid','high']])

# Target encoding (category_encoders)
from category_encoders import TargetEncoder
TargetEncoder(smoothing=1.0)
Dummy trap: Always drop one column with One-Hot Encoding for linear models β€” use drop='first'. Tree models don't need this.

Feature Scaling

Scaling
MethodFormulaOutput RangeUse When
Min-Max(xβˆ’min)/(maxβˆ’min)[0, 1]Bounded output needed, no outliers
Standardization(xβˆ’ΞΌ)/Οƒ~(βˆ’3, 3)Normal distribution, outliers ok
Robust Scaler(xβˆ’median)/IQRUnboundedHeavy outliers present
Max-Abs Scalerx / max(|x|)[βˆ’1, 1]Sparse data β€” doesn't center
Log Transformlog(x + 1)UnboundedRight-skewed (income, counts)
Box-CoxOptimal power transformUnboundedPositive values, normalise distribution
sklearn
from sklearn.preprocessing import (
  StandardScaler, MinMaxScaler,
  RobustScaler, PowerTransformer)

StandardScaler()          # z-score
MinMaxScaler(feature_range=(0,1))
RobustScaler()            # IQR-based
PowerTransformer(method='box-cox')
Critical: Always fit on training data only, then transform both train and test. Never fit on test β€” it causes data leakage.

Missing Value Imputation

Imputation
StrategyFill WithBest For
MeanColumn meanNumerical, normally distributed, few missing
MedianColumn medianNumerical with outliers or skewed
ModeMost frequent valueCategorical features
ConstantFixed value (0, "Unknown")When missing = meaningful signal
KNN Imputerk-nearest neighboursSmall datasets, preserves relationships
IterativeModel each featureComplex MAR data β€” best but slow
sklearn
from sklearn.impute import (
  SimpleImputer, KNNImputer, IterativeImputer)

SimpleImputer(strategy='median')
SimpleImputer(strategy='most_frequent')
SimpleImputer(strategy='constant',
  fill_value='Unknown')
KNNImputer(n_neighbors=5)
IterativeImputer(max_iter=10)
Missing indicator: Add a binary column flagging which rows were imputed β€” the missingness itself may be predictive.

Feature Creation

Engineering
TechniqueExample
Arithmeticprice_per_sqft = price / area
Ratiosctr = clicks / impressions
Binningage β†’ [0–18, 19–35, 36–60, 60+]
Log transformlog1p(revenue) β€” normalise skew
PolynomialxΒ², xΒ·y β€” capture non-linearity
Interactionage Γ— income β€” joint effect
Datetimehour, dayofweek, month, is_weekend, quarter
Cyclic encodesin/cos of hour, month β€” preserves circularity
Aggregationsuser mean spend, category purchase count
Lag featuresprevious day's sales, rolling 7-day avg
Cyclic Encoding β€” Hours
import numpy as np
# Hour 0 and 23 are close β€” sin/cos keeps this
df['hour_sin'] = np.sin(2*np.pi*df['hour']/24)
df['hour_cos'] = np.cos(2*np.pi*df['hour']/24)

Handling Outliers

Data Quality
Detection MethodRuleBest For
IQR MethodOutside [Q1βˆ’1.5Β·IQR, Q3+1.5Β·IQR]Skewed distributions
Z-Score|z| > 3Normally distributed data
Modified Z-Score|0.6745Β·(xβˆ’median)/MAD| > 3.5Small datasets, robust
Isolation ForestML-based anomaly detectionHigh-dimensional data
TreatmentWhen
RemoveClearly wrong / data entry error
Cap / WinsoriseKeep value, clip to percentile (e.g. 1st–99th)
Log transformCompress scale without removing
Robust modelUse MAE loss or tree-based models β€” outlier-resistant
Keep + flagAdd binary is_outlier feature β€” signal may be useful
Winsorising with pandas
lower = df['price'].quantile(0.01)
upper = df['price'].quantile(0.99)
df['price'] = df['price'].clip(lower, upper)

Feature Selection

Selection
MethodTypeHow
Variance ThresholdFilterRemove near-zero variance features
Correlation FilterFilterRemove features correlated > 0.9 with another
Chi-SquareFilterTest independence with target (classification)
ANOVA F-testFilterTest mean differences across classes
Mutual InformationFilterCaptures non-linear relationships
RFEWrapperRecursively removes weakest features
Lasso (L1)EmbeddedShrinks irrelevant coefficients to zero
Tree ImportanceEmbeddedFeature importance from RF / XGBoost
SHAPEmbeddedModel-agnostic importance β€” most reliable
sklearn β€” SelectKBest + RFE
from sklearn.feature_selection import (
  SelectKBest, f_classif,
  RFE, mutual_info_classif)

# Filter β€” top 10 by ANOVA F
SelectKBest(f_classif, k=10)

# Wrapper β€” recursive elimination
RFE(estimator=LogisticRegression(),
  n_features_to_select=10)

Dimensionality Reduction

Reduction
MethodTypeBest For
PCALinearVariance preservation, multicollinearity, preprocessing
t-SNENon-linearVisualisation (2D/3D) β€” not for preprocessing
UMAPNon-linearFaster t-SNE, preserves global structure better
LDASupervisedMaximise class separability
AutoencoderNeuralComplex non-linear compression
Truncated SVDLinearSparse data (NLP/TF-IDF)
PCA β€” Explained Variance
Choose n_components where Ξ£ explained_variance_ratio_ β‰₯ 0.95
Each principal component is orthogonal β€” no multicollinearity
sklearn PCA
from sklearn.decomposition import PCA

# Keep 95% variance
pca = PCA(n_components=0.95)
X_reduced = pca.fit_transform(X_train)

# Explained variance per component
pca.explained_variance_ratio_
pca.n_components_  # how many chosen
PCA requires scaling first β€” features must be standardised or PCA will be dominated by high-magnitude features.

Full sklearn Pipeline β€” Numeric + Categorical

Pipeline
Complete Production Pipeline
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import (
  StandardScaler, OneHotEncoder)
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier

num_cols = ['age', 'income', 'score']
cat_cols = ['city', 'gender']

# Numeric pipeline
num_pipe = Pipeline([
  ('impute', SimpleImputer(strategy='median')),
  ('scale',  StandardScaler())
])

# Categorical pipeline
cat_pipe = Pipeline([
  ('impute', SimpleImputer(strategy='most_frequent')),
  ('encode', OneHotEncoder(drop='first',
               handle_unknown='ignore'))
])
Assemble + Train + Evaluate
# Combine with ColumnTransformer
preprocessor = ColumnTransformer([
  ('num', num_pipe, num_cols),
  ('cat', cat_pipe, cat_cols)
])

# Full pipeline with model
pipe = Pipeline([
  ('prep',  preprocessor),
  ('model', RandomForestClassifier(
             n_estimators=200))
])

# Fit β€” all transforms fit on train only
pipe.fit(X_train, y_train)

# Evaluate β€” transform applied automatically
pipe.score(X_test, y_test)

# Cross-validate the full pipeline
from sklearn.model_selection import cross_val_score
cross_val_score(pipe, X, y, cv=5)
Why pipelines? Prevents data leakage β€” scalers and encoders fit only on training folds inside CV, not on the full dataset. Always use a pipeline in production.

Class Imbalance in Features

Imbalance
TechniqueHowWhen
SMOTESynthetic minority oversamplingTabular, severe imbalance
ADASYNAdaptive synthetic samplingComplex decision boundaries
Random UndersamplingRemove majority samplesLarge dataset
Class Weightsclass_weight='balanced'Quick, no data modification
Threshold TuningLower decision thresholdPost-training adjustment
imbalanced-learn β€” SMOTE Pipeline
from imblearn.pipeline import Pipeline as ImbPipeline
from imblearn.over_sampling import SMOTE

pipe = ImbPipeline([
  ('prep',  preprocessor),
  ('smote', SMOTE(random_state=42)),
  ('model', RandomForestClassifier())
])
Use imblearn Pipeline not sklearn Pipeline when SMOTE is involved β€” it applies oversampling only to training folds, not validation folds inside CV.

Text & Datetime Features

Special Types
Datetime Feature Extraction
df['year']       = df['date'].dt.year
df['month']      = df['date'].dt.month
df['dayofweek']  = df['date'].dt.dayofweek
df['is_weekend'] = df['dayofweek'] >= 5
df['quarter']    = df['date'].dt.quarter
df['days_since']  = (pd.Timestamp.now()
                   - df['date']).dt.days
Text β€” TF-IDF + Bag of Words
from sklearn.feature_extraction.text import (
  TfidfVectorizer, CountVectorizer)

# Bag of Words
CountVectorizer(max_features=5000,
  ngram_range=(1,2))  # unigrams+bigrams

# TF-IDF (preferred)
TfidfVectorizer(max_features=5000,
  stop_words='english',
  sublinear_tf=True)
Word Embeddings: For richer text features use pre-trained embeddings β€” Word2Vec, GloVe, FastText, or sentence-transformers (BERT-based).

Feature Engineering Mastery Checklist

Self-Assessment

Encoding & Scaling

Choose the right encoding for nominal, ordinal, and high-cardinality features
Apply One-Hot encoding and drop the first column to avoid the dummy trap
Use Target Encoding with smoothing to avoid target leakage
Apply StandardScaler, MinMaxScaler, and RobustScaler correctly
Know which algorithms need scaling and which don't
Apply log/Box-Cox transform to right-skewed features

Imputation

Impute numerical features with median (outlier-robust)
Impute categorical features with mode or constant
Add a missing indicator flag when missingness is informative
Use KNNImputer or IterativeImputer for complex missing patterns

Feature Creation

Create ratio and interaction features from domain knowledge
Extract datetime components (hour, dayofweek, is_weekend, quarter)
Apply cyclic encoding (sin/cos) for periodic features like hour and month
Bin continuous features when relationship with target is non-monotonic
Create lag and rolling window features for time-series data

Outliers

Detect outliers using IQR and Z-score methods
Winsorise features at 1st and 99th percentile
Decide between removing, capping, transforming, or flagging outliers

Selection & Reduction

Remove near-zero variance and highly correlated features
Apply SelectKBest with f_classif or mutual_info_classif
Use RFE to recursively select the most important features
Use Lasso or tree importance for embedded feature selection
Apply PCA after scaling and choose n_components for 95% variance
Use SHAP values for reliable model-agnostic feature importance

Pipelines

Build a ColumnTransformer for separate numeric and categorical pipelines
Wrap everything in a sklearn Pipeline to prevent leakage in CV
Use imblearn Pipeline when SMOTE is part of the workflow
Cross-validate the full pipeline β€” not just the model step

πŸŽ‰ You've completed the ML Fundamentals series!

Next: explore Deep Learning, NLP, Computer Vision, Time Series, and Reinforcement Learning series on Dataplexa.
Browse All Cheat Sheets β†’
← Back