A food delivery app knows when each order was placed, as a timestamp like "2026-03-07 20:45". A model can't do much with that string. But a person looking at it sees useful facts straight away: it's 8:45 in the evening, it's a Saturday, it's dinner rush. Those facts are what really affect delivery time.
Feature engineering is turning raw columns into features that make the pattern easy for a model to see. It's where your knowledge of the problem goes into the model. On tabular data, a few good features often help more than switching to a fancier algorithm. The feature engineering basics come down to a few moves: date and time parts, distances, ratios, log transforms and bins. You'll test each on real house prices, and see the case where new features make a model worse.
What you need first: scikit-learn tutorial, skewed data and log transforms and encoding categorical data.
Key terms
- Feature engineering: creating new features from existing columns, using knowledge of the problem.
- Derived feature: a feature calculated from others, such as price per item from subtotal and items.
- Log transform: replacing a value x with log(x), which squeezes very large values closer together.
- Binning: grouping a number into ranges, such as house age 0–10, 10–30 and 30+ years.
- Row-wise feature: a feature calculated from one row alone. It learns nothing from other rows, so it can't leak information between training and test data.
Start from what a person would notice
Here are four delivery orders in Bengaluru, with the restaurant and customer locations as map coordinates (latitude and longitude):
import numpy as np
import pandas as pd
orders = pd.DataFrame({
"order_time": ["2026-03-06 13:10", "2026-03-07 20:45", "2026-03-08 21:30", "2026-03-09 09:05"],
"restaurant_lat": [12.9716, 12.9352, 12.9611, 12.9250],
"restaurant_lon": [77.5946, 77.6245, 77.6387, 77.5938],
"customer_lat": [12.9784, 12.9081, 12.9698, 12.9352],
"customer_lon": [77.6408, 77.6476, 77.7500, 77.6245],
"items": [2, 5, 3, 1],
"subtotal_rs": [380, 1250, 640, 150],
"minutes": [28, 41, 47, 22],
})
print(orders[["order_time", "items", "subtotal_rs", "minutes"]])
order_time items subtotal_rs minutes
0 2026-03-06 13:10 2 380 28
1 2026-03-07 20:45 5 1250 41
2 2026-03-08 21:30 3 640 47
3 2026-03-09 09:05 1 150 22
Ask what actually changes delivery time. The time of day (traffic, kitchen rush). Whether it's a weekend. How far the food has to travel. None of these is a column yet, and all of them can be made from the columns you have.
Dates and times: split them into parts
pd.to_datetime turns the text into real dates. The .dt accessor then pulls out parts of each date:
when = pd.to_datetime(orders["order_time"])
orders["hour"] = when.dt.hour
orders["day_of_week"] = when.dt.dayofweek # Monday = 0, Sunday = 6
orders["is_weekend"] = (orders["day_of_week"] >= 5).astype(int)
print(orders[["order_time", "hour", "day_of_week", "is_weekend"]])
order_time hour day_of_week is_weekend
0 2026-03-06 13:10 13 4 0
1 2026-03-07 20:45 20 5 1
2 2026-03-08 21:30 21 6 1
3 2026-03-09 09:05 9 0 0
The 20:45 order is now "hour 20, Saturday, weekend": three numbers a model can use. astype(int) turns True/False into 1 and 0. Clean dates and times covers dates in more depth.
Distances: combine coordinates into one meaningful number
Four coordinate columns don't tell a model "how far". One distance column does. Over a city, you can treat the map as flat: one degree of latitude is about 111 km, and one degree of longitude is about 111 × cos(latitude) km (lines of longitude get closer together away from the equator). Then use Pythagoras:
def distance_km(lat1, lon1, lat2, lon2):
north_km = (lat2 - lat1) * 111
east_km = (lon2 - lon1) * 111 * np.cos(np.radians(lat1))
return np.sqrt(north_km ** 2 + east_km ** 2)
orders["distance_km"] = distance_km(orders["restaurant_lat"], orders["restaurant_lon"],
orders["customer_lat"], orders["customer_lon"]).round(1)
print(orders[["distance_km", "minutes"]])
distance_km minutes
0 5.1 28
1 3.9 41
2 12.1 47
3 3.5 22
np.radians converts degrees to the unit np.cos expects. Now there's something to see even in four rows: the 12.1 km order took longest, 47 minutes. But the 3.9 km order took 41 minutes, much longer than the 3.5 km one. Look back at the time features: it was Saturday at 20:45, dinner rush. Distance alone doesn't explain delivery time, which is why you make several features, not one. This flat-map formula is accurate to well under 1% across a city; for distances between cities you'd use the haversine formula, which accounts for the Earth being round.
Ratios: per-item, per-person, per-room
Sometimes the useful number is one column divided by another:
orders["rs_per_item"] = (orders["subtotal_rs"] / orders["items"]).round(0)
print(orders[["items", "subtotal_rs", "rs_per_item"]])
items subtotal_rs rs_per_item
0 2 380 190.0
1 5 1250 250.0
2 3 640 213.0
3 1 150 150.0
₹250 per item suggests full meals; ₹150 for one item might be a snack. A model given only "subtotal" and "items" separately would have to work out the ratio itself, and simple models like linear regression can't: they only add up weighted features, they never divide one by another.
All three of these features are row-wise: each one uses only its own row. That makes them safe to create before splitting the data, because no row learns anything from any other row.
A real test: California house prices
Ideas are cheap. Every feature must earn its place by improving the score on data the model hasn't seen. The California housing data has 20,640 districts, eight features, and the median house value in each district (in units of $100,000).
Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("california-housing.csv").
fetch_california_housing downloads the data the first time and saves a copy; as_frame=True gives a pandas DataFrame instead of a bare array:
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
housing = fetch_california_housing(as_frame=True)
X, y = housing.data.copy(), housing.target
print(X.columns.tolist())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
def test_mae(columns):
"""Fit a linear regression on the chosen columns; return the test MAE in dollars."""
model = LinearRegression().fit(X_train[columns], y_train)
return round(mean_absolute_error(y_test, model.predict(X_test[columns])) * 100_000)
original = housing.feature_names
print(f"original 8 features: test MAE ${test_mae(original):,}")
['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']
original 8 features: test MAE $53,690
MAE is the mean absolute error: the average size of a prediction's mistake, here converted to dollars. (Recall from loss functions explained that it's the average of |prediction − truth|.) On average, the model is off by about $53,700. That's the number to beat.
Feature 1: distance to the nearest big city
The data has latitude and longitude, but house prices don't rise in a straight line as you go north or east. They're highest near Los Angeles and San Francisco, and fall away from them. A linear model can't learn "near a city" from raw coordinates. A distance can tell it directly.
Predict: will adding "distance to the nearest of LA and San Francisco" lower the error a lot, a little, or not at all?
X["dist_la"] = distance_km(34.05, -118.24, X["Latitude"], X["Longitude"])
X["dist_sf"] = distance_km(37.77, -122.42, X["Latitude"], X["Longitude"])
X["dist_city"] = X[["dist_la", "dist_sf"]].min(axis=1) # whichever city is nearer
X["log_dist_city"] = np.log1p(X["dist_city"])
X_train, X_test = X.loc[X_train.index], X.loc[X_test.index] # same rows as before, new columns
print(f"+ distance: ${test_mae(original + ['dist_city']):,}")
print(f"+ log distance: ${test_mae(original + ['log_dist_city']):,}")
+ distance: $53,217
+ log distance: $52,533
A little. min(axis=1) takes the smaller of the two distances in each row. np.log1p(x) means log(1 + x); the "+1" keeps it safe when a distance is 0. The rows of the train and test sets are re-selected by their index, so the split stays exactly the same and the comparison is fair.
The log version helps more. Look at the picture to see why:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), sharey=True)
sample = X.sample(3000, random_state=0)
axes[0].scatter(sample["dist_city"], y[sample.index], s=5, alpha=0.3, color="#c2410c")
axes[0].set_xlabel("Distance to LA or SF (km)")
axes[0].set_ylabel("Median house value ($100,000s)")
axes[0].set_title("Raw distance")
axes[1].scatter(sample["log_dist_city"], y[sample.index], s=5, alpha=0.3, color="#0f766e")
axes[1].set_xlabel("log(1 + distance)")
axes[1].set_title("Log distance")
plt.show()
On the left, value drops steeply in the first 100 km or so, then flattens: being 20 km from the city instead of 10 matters a lot, but 420 km instead of 410 matters very little. That's a curve, and a straight line fits it poorly. The log stretches out the short distances and squeezes the long ones, so the relationship becomes closer to a straight line.
Feature 2: fix a badly skewed column
Now look at AveOccup, the average number of people per household:
print(X["AveOccup"].describe().round(1))
count 20640.0
mean 3.1
std 10.4
min 0.7
25% 2.4
50% 2.8
75% 3.3
max 1243.3
Name: AveOccup, dtype: float64
Half the districts have between 2.4 and 3.3 people per household, but the maximum is 1,243. That's not a real household; it's probably a district with a hostel, prison or army camp. In a linear model, a few huge values like that pull the line towards them. Predict: will a log transform of this column help more or less than the distance did?
X["log_occupancy"] = np.log(X["AveOccup"])
X_train, X_test = X.loc[X_train.index], X.loc[X_test.index]
without_occ = [c for c in original if c != "AveOccup"]
print(f"log occupancy instead of raw: ${test_mae(without_occ + ['log_occupancy']):,}")
log occupancy instead of raw: $49,768
More, by a lot. Taking logs turned 1,243 into about 7, so those few odd districts no longer dominate. (np.log is fine here because every value is above 0; use np.log1p when a column can be 0.) Skewed data and log transforms explains why logs tame long tails.
Put it together
engineered = without_occ + ["log_occupancy", "log_dist_city"]
X["bedroom_share"] = X["AveBedrms"] / X["AveRooms"]
X["log_population"] = np.log(X["Population"])
X_train, X_test = X.loc[X_train.index], X.loc[X_test.index]
more = engineered + ["bedroom_share", "log_population"]
print(f"original: ${test_mae(original):,}")
print(f"+ log occupancy, dist: ${test_mae(engineered):,}")
print(f"+ bedroom share, log population: ${test_mae(more):,}")
original: $53,690
+ log occupancy, dist: $47,972
+ bedroom share, log population: $47,424
Same algorithm, same rows, an error about $6,000 lower per district, just from better features. Not every idea helps equally: the occupancy fix did most of the work, and each extra feature added less. That's normal.
Bins: when the effect comes in steps
Sometimes a number matters in ranges rather than smoothly. For example, the age of a house might matter as "new", "settled" and "old" rather than year by year. pd.cut groups numbers into ranges you choose:
age_band = pd.cut(X["HouseAge"], bins=[0, 10, 30, 52], labels=["new", "settled", "old"])
print(age_band.value_counts().sort_index())
HouseAge
new 1569
settled 9576
old 9495
Name: count, dtype: int64
bins=[0, 10, 30, 52] means the ranges 0–10, 10–30 and 30–52 (each includes its upper edge). The bands are then categories, so you'd one-hot encode them before a linear model uses them.
Bins with fixed edges you choose, like these, are row-wise and safe. Bins whose edges are learned from the data, such as "split into four equal-sized groups", are not: the edges must be learned from the training rows only, exactly like a scaler. Scikit-learn's KBinsDiscretizer is a transformer that does this with fit and transform.
When new features make things worse
More features aren't always better. Each one is another thing the model can fit by chance. To see it fail, give a model only 300 training rows, then add columns of pure random noise:
rng = np.random.default_rng(0)
small_train = X_train[original].iloc[:300]
small_y = y_train.iloc[:300]
for extra in [0, 50, 250]:
noise_train = rng.normal(size=(300, extra))
noise_test = rng.normal(size=(len(X_test), extra))
train_X = np.hstack([small_train.values, noise_train])
test_X = np.hstack([X_test[original].values, noise_test])
model = LinearRegression().fit(train_X, small_y)
train_mae = mean_absolute_error(small_y, model.predict(train_X)) * 100_000
test_err = mean_absolute_error(y_test, model.predict(test_X)) * 100_000
print(f"{extra:3} noise features: train MAE ${train_mae:,.0f} test MAE ${test_err:,.0f}")
0 noise features: train MAE $53,243 test MAE $56,020
50 noise features: train MAE $48,005 test MAE $64,976
250 noise features: train MAE $19,566 test MAE $182,000
np.hstack glues arrays side by side. As noise columns are added, the training error falls, because the model uses the random numbers to fit the 300 training rows more closely. The test error rises, because those random patterns don't exist in new data. With 250 noise features and only 300 rows, the model has almost as many weights as examples, and it memorises.
This is overfitting, the subject of the "How models learn" module. For feature engineering, the lesson is: judge every new feature by the test (or validation) score, never by the training score, and be more careful with features the smaller your dataset is.
A feature engineering toolkit
| Raw column | Feature to try | Why it helps |
|---|---|---|
| Timestamp | Hour, day of week, month, is_weekend, is_holiday | Behaviour follows the clock and calendar |
| Two timestamps | Gap between them (days since last order) | Recency often predicts what happens next |
| Coordinates | Distance to a key place | "Near" is what matters, not raw position |
| Two related amounts | Ratio (per item, per person, per room) | Linear models can't divide one feature by another |
| Long-tailed amount (income, population) | log(x) or log(1 + x) | Stops a few huge values dominating |
| Number with step effects | Bins, then one-hot | Captures jumps a straight line misses |
| Text | Length, word counts, "contains a keyword" | Turns text into numbers simply |
| Two features that act together | Product (area × quality) | Lets a linear model see "both high" |
Common mistakes
- Judging a feature by training score. Training error almost always falls when you add a column. Only the test or validation score counts.
- Learning from all the data. Bins by quantile, "average price of this area", or anything else learned from many rows must be learned from training rows only. Otherwise it's data leakage.
- Features you won't have at prediction time. "Delivery rider's actual route" is a great predictor and useless in real life.
np.logof zero or negative values. It gives-infornan. Usenp.log1pfor counts that can be 0.- Too many features on a small dataset. With 300 rows, 250 extra columns let the model memorise.
Practice
- A cricket app has each batter's
runsandballs_facedfor every innings. Suggest one engineered feature, and say why a linear model couldn't work it out alone.
Show the answer
Strike rate = runs ÷ balls faced × 100. A linear model can only add weighted features (a × runs + b × balls), so it can't divide one by the other. Giving it the ratio directly hands it the fact that matters: how quickly the batter scores.
- For the delivery orders above, add a feature
is_dinnerthat's 1 for orders placed from 19:00 to 22:59 and 0 otherwise.
Show the answer
orders["is_dinner"] = orders["hour"].between(19, 22).astype(int)
print(orders[["hour", "is_dinner"]])
hour is_dinner
0 13 0
1 20 1
2 21 1
3 9 0
between(19, 22) includes both ends, so hours 19, 20, 21 and 22 count, which covers 19:00 to 22:59.
- Predict: you add a column of random numbers to the full California training set (15,480 rows) and refit. Will the test MAE change much? Why is this different from the 300-row experiment?
Show the answer
Hardly at all. With 15,480 rows, one random column can't fit much by chance: its weight ends up close to 0. With 300 rows and 250 random columns, the model had nearly one weight per row, so it could fit noise. Noise features hurt most when there are few rows per feature.
- Someone computes "average house value in this district's latitude band" using all 20,640 rows, then splits into train and test. What's wrong?
Show the answer
The feature was calculated using the test rows' house values, which are the labels the model is meant to predict. Test rows have helped make their own features, so the test score will be too optimistic. Compute it from the training rows only, then apply those averages to the test rows.
- Why did the log of distance help a linear model more than the raw distance?
Show the answer
House value falls steeply within the first 100 km of a big city and then levels off, which is a curve. A linear model fits straight lines. The log stretches short distances and squeezes long ones, so the relationship between log distance and value is much closer to a straight line.
- Is
rs_per_item(subtotal ÷ items) safe to create before splitting into train and test sets? What about "this restaurant's average delivery time"?
Show the answer
rs_per_item uses only its own row, so it's safe. "This restaurant's average delivery time" is computed across many orders, including test orders, and uses the label itself (delivery time). It must be calculated from training orders only, and even then only from orders that happened before the one being predicted.
Interview questions
What is feature engineering, and why does it matter?
Creating new input features from raw data using domain knowledge, such as date parts, ratios, distances, aggregates and transformations. It matters because models can only learn patterns that are reachable from their inputs: a well-chosen feature can make a simple model accurate, especially on tabular data, where it often beats changing the algorithm.
How do you decide whether a new feature is worth keeping?
Compare validation or cross-validation scores with and without it, using the same splits. Keep it if it improves the score by more than the normal variation between folds, makes sense for the problem, and will be available at prediction time. Never decide using training scores or the test set.
Key takeaways
- Feature engineering turns raw columns into facts that make the pattern easy to see: date parts, distances, ratios, logs, bins.
- Linear models can't divide, take logs or measure distance by themselves; good features do it for them.
- Every feature must improve the score on unseen data; training scores always look better.
- Row-wise features are safe to create before splitting; anything learned from many rows must be fit on training data only.
- Extra features can hurt, especially on small datasets: 250 noise columns let a model memorise 300 rows.
Frequently asked questions
Do tree-based models need feature engineering?
Less of it. Decision trees and gradient boosting handle curves, steps and skewed values on their own, so logs and bins matter less. Ratios, distances, date parts and aggregates still help them, because those add information that isn't in any single column.
What's the difference between feature engineering and feature selection?
Feature engineering creates new features. Feature selection removes features that don't help. They're used together: engineer candidates, then keep the ones that improve validation scores.
Is feature engineering still needed with deep learning?
For images, audio and text, deep learning learns its own features from raw data, so much less hand-crafting is needed. For tables of business data, careful feature engineering is still one of the most effective things you can do.
What to learn next
- Scikit-learn pipelines: package feature steps and the model together.
- Data leakage: the features and steps that quietly cheat.
- Feature scaling: the other preprocessing step most models need.