Feature engineering is creating and transforming input columns so a model can learn more easily. Good features often improve results more than switching algorithms.
What You Will Learn
- Binning numbers into groups
- Flag (boolean) features
- One-hot encoding categories
- Scaling
- Measuring the gain with cross-validation
- Avoiding leakage with pipelines
Prerequisites
Outlier Detection – we use the cleaned emp.csv data.
Start with Clean Data
import pandas as pd
df = pd.read_csv("emp.csv")
clean = df[df.salary < 120850].copy() # drop the error row and missing salaries
Create Features
fe = clean.copy()
fe["exp_level"] = pd.cut(fe.experience, bins=[-1, 2, 7, 15, 40],
labels=["Fresher", "Junior", "Mid", "Senior"])
fe["is_metro"] = fe.city.isin(["Delhi", "Mumbai"]).astype(int)
fe = pd.get_dummies(fe, columns=["city"], drop_first=True, dtype=int)
print(fe.head().to_string())
age experience salary exp_level is_metro city_Ludhiana city_Mumbai 0 24 18 76200.0 Senior 1 0 1 1 51 23 78700.0 Senior 1 0 0 2 46 22 75100.0 Senior 0 1 0 3 38 4 34300.0 Junior 1 0 1 4 37 24 72900.0 Senior 1 0 1
Explanation: pd.cut bins experience into levels; is_metro is a simple flag; get_dummies one-hot encodes city. drop_first=True removes Delhi as the reference category to avoid redundant columns in linear models.
Does It Help? Measure It
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
y = clean.salary
X1 = clean[["experience"]]
X2 = pd.get_dummies(clean[["experience", "city"]], drop_first=True, dtype=int)
for name, X in [("experience only", X1), ("experience + city", X2)]:
print(name, round(cross_val_score(LinearRegression(), X, y, cv=5, scoring="r2").mean(), 3))
experience only 0.869 experience + city 0.909
Explanation: Adding the encoded city raises cross-validated R² from 0.869 to 0.909, because Mumbai salaries are higher. Always judge features with cross-validation, not by intuition.
Common Techniques
| Type | Technique | pandas / sklearn |
|---|---|---|
| Numeric | Scaling | StandardScaler, MinMaxScaler |
| Log transform for skew | np.log1p | |
| Binning | pd.cut, pd.qcut | |
| Interactions / ratios | df.a * df.b, df.a / df.b | |
| Categorical | One-hot | pd.get_dummies, OneHotEncoder |
| Ordinal | OrdinalEncoder (for ordered levels) | |
| Target encoding | TargetEncoder (sklearn 1.3+) | |
| Date/time | Parts and gaps | .dt.month, .dt.dayofweek, days since – datetime |
| Text | Counts / TF-IDF / embeddings | TfidfVectorizer |
| Missing | Indicator + impute | SimpleImputer(add_indicator=True) |
Avoid Leakage with a Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pre = ColumnTransformer([("num", StandardScaler(), ["age", "experience"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"])])
model = Pipeline([("prep", pre), ("reg", LinearRegression())])
print(round(cross_val_score(model, clean[["age", "experience", "city"]], y, cv=5).mean(), 3))
0.908
Explanation: Same R² as before (age adds nothing), but now safely: a pipeline fits the scaler and encoder only on the training part of each fold, so no information from validation data leaks in. It also applies the same steps automatically at prediction time.
Series
Data Science series: What is Data Science · Lifecycle · Data Cleaning · EDA · Outliers · Feature Engineering · Visualization · Seaborn · Roadmap
Interview Questions
Q: What is feature engineering?
Creating and transforming input variables to help a model learn the underlying pattern.
Q: One-hot vs ordinal encoding?
One-hot for unordered categories; ordinal integers for ordered categories like Low/Medium/High.
Q: How do pipelines prevent leakage?
They fit preprocessing on training folds only and reuse the fitted steps for validation and test data.
Practice Exercises
- Add an “experience²” feature and check whether R² improves.
- Build features from a date column: month, weekday and days since signup.
Summary
Bin, flag, encode, scale and transform features, measure every change with cross-validation and wrap the steps in a pipeline to avoid leakage.
Next: Data Preprocessing · Seaborn Tutorial
Machine Learning Tutorials, Courses and Certifications