Lesson 64 · Pandas Full Course
Predict House Prices with Pandas and scikit-learn (End-to-End Project) | Pandas Course #64
In this lesson you'll be able to: Explore a prediction target and spot capped values Engineer ratio features that make districts comparable Turn text…
- CoursePandas Full Course
- Lesson64 of 65
- FormatJupyter notebook · 42 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- housing.csv preview1.4 MB
📓 Full notebook
Download .ipynbPandas 64: Hands-on Project - Predicting House Prices#
In this lesson you'll be able to:
- Explore a prediction target and spot capped values
- Engineer ratio features that make districts comparable
- Turn text categories into model-ready numbers
- Split, fill and fit without leaking test data
- Judge a model against a baseline, and find where it fails Dataset: California housing, 20,640 districts (data/pandas/housing.csv)
Warm-up: summarise by group#
Lesson 63 compared groups with totals and shares. Same skills, new data.
import pandas as pd
df = pd.read_csv("data/pandas/housing.csv")
print(df.shape)
df[["median_income", "median_house_value", "ocean_proximity"]].head(3)
target = "median_house_value"
loc = df.groupby("ocean_proximity")[target].agg(["size", "median"])
loc["share"] = loc["size"] / loc["size"].sum()
loc.sort_values("median").round(2)
Understand the target before predicting it#
Problem: a model can only be as good as the numbers it learns from.
cols = ["median_income", "housing_median_age", target]
df[cols].describe().round(2)
Quick check: which house value appears most often?
df[target].value_counts().head(3)
import matplotlib.pyplot as plt
ax = df[target].plot(kind="hist", bins=50, figsize=(7, 4))
ax.set_title("Median house value per district")
ax.set_xlabel("Median house value (dollars)")
ax.set_ylabel("Number of districts")
plt.show()
capped = df[target] >= 500001
print(capped.sum())
df = df[~capped].copy()
print(len(df))
old = df["housing_median_age"] == 52
print(old.sum())
print(round(df.loc[old, target].median()))
Engineer features that describe a typical home#
Problem: totals grow with district size, not with how nice homes are.
df["rooms_per_house"] = df["total_rooms"] / df["households"]
df["bedroom_ratio"] = df["total_bedrooms"] / df["total_rooms"]
df["people_per_house"] = df["population"] / df["households"]
new = ["rooms_per_house", "bedroom_ratio", "people_per_house"]
df[new].describe().round(2)
show = ["people_per_house", "population", "households", target]
df.nlargest(3, "people_per_house")[show].round(1)
Common mistake: asking for correlations with a text column present
df.corr()[target]
corr = df.corr(numeric_only=True)[target]
corr.drop(target).sort_values().round(3)
sample = df.sample(2000, random_state=42)
ax = sample.plot(kind="scatter", x="median_income", y=target,
alpha=0.3, figsize=(7, 4))
ax.set_title("Richer districts have pricier homes")
ax.set_xlabel("Median income (tens of thousands of dollars)")
ax.set_ylabel("Median house value (dollars)")
plt.show()
Your turn#
Cut median_income into 5 equal-width bands and find the median value in each.
bands = pd.cut(df["median_income"], bins=5)
by_band = df.groupby(bands, observed=True)[target]
by_band.agg(["size", "median"]).round(0)
Turn location text into numbers#
Problem: models do arithmetic, and you can't multiply a word.
Common mistake: giving a model a text column
from sklearn.linear_model import LinearRegression
LinearRegression().fit(df[["median_income", "ocean_proximity"]],
df[target])
dummies = pd.get_dummies(df["ocean_proximity"], dtype=int)
dummies.head(3)
Quick check: how many districts are in each new column?
dummies.sum()
cols = ["median_income", target]
df.groupby("ocean_proximity")[cols].median().round(2)
features = ["median_income", "housing_median_age", "latitude",
"longitude"] + new
X = pd.concat([df[features], dummies], axis=1)
y = df[target]
print(X.shape)
X.dtypes.value_counts()
Split before you fill: train and test sets#
Problem: a model must be tested on districts it has never seen.
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)
print(X_train.shape, X_test.shape)
print(round(y_train.mean()), round(y_test.mean()))
print(round(X_train["INLAND"].mean(), 3))
print(round(X_test["INLAND"].mean(), 3))
Common mistake: fitting with missing values
model = LinearRegression().fit(X_train, y_train)
ratio_med = X_train["bedroom_ratio"].median()
X_train = X_train.fillna({"bedroom_ratio": ratio_med})
X_test = X_test.fillna({"bedroom_ratio": ratio_med})
print(X_train.isna().sum().sum(), X_test.isna().sum().sum())
Quick check: why use the training median, not the whole dataset's?
all_med = df["bedroom_ratio"].median()
print(round(ratio_med, 4), round(all_med, 4))
Fit a model and judge it fairly#
Problem: an error number means nothing without a baseline to beat.
from sklearn.metrics import mean_absolute_error
guess = pd.Series(y_train.median(), index=y_test.index)
base_mae = mean_absolute_error(y_test, guess)
print(f"Baseline error: {base_mae:,.0f}")
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
lin_mae = mean_absolute_error(y_test, pred)
print(f"Linear error: {lin_mae:,.0f}")
Quick check: is that error big compared with a typical home?
print(round(lin_mae / y_test.median(), 3))
weights = pd.Series(model.coef_, index=X_train.columns)
weights[["median_income", "housing_median_age", "INLAND"]].round(0)
res = pd.DataFrame({"actual": y_test, "predicted": pred})
res["error"] = res["predicted"] - res["actual"]
res.head().round(0)
ax = res.plot(kind="scatter", x="actual", y="predicted",
alpha=0.2, figsize=(6, 5))
ax.plot([0, 500000], [0, 500000], color="red")
ax.set_title("Linear model: predicted vs actual value")
ax.set_xlabel("Actual value (dollars)")
ax.set_ylabel("Predicted value (dollars)")
plt.show()
Your turn#
Fit a RandomForestRegressor (100 trees, random_state=42). Does it beat the line?
from sklearn.ensemble import RandomForestRegressor
forest = RandomForestRegressor(n_estimators=100, random_state=42)
forest.fit(X_train, y_train)
res["forest"] = forest.predict(X_test)
forest_mae = mean_absolute_error(y_test, res["forest"])
print(f"Forest error: {forest_mae:,.0f}")
from sklearn.metrics import r2_score
print(round(r2_score(y_test, pred), 3))
print(round(r2_score(y_test, res["forest"]), 3))
imp = pd.Series(forest.feature_importances_, index=X_train.columns)
imp.nlargest(5).round(3)
Common mistake: predicting with different columns than you fitted
forest.predict(X_test[["median_income", "latitude", "longitude"]])
one = X_test.iloc[[0]]
print(round(forest.predict(one)[0]))
print(round(y_test.iloc[0]))
Mini-project: where does the model go wrong?#
Plan: attach location to each error, group, then summarise.
res["miss"] = (res["forest"] - res["actual"]).abs()
res["bias"] = res["forest"] - res["actual"]
res["place"] = df.loc[res.index, "ocean_proximity"]
res[["actual", "forest", "miss", "place"]].head(3).round(0)
by_place = res.groupby("place")[["actual", "miss", "bias"]].mean()
by_place["miss_pct"] = by_place["miss"] / by_place["actual"]
by_place.sort_values("miss_pct").round(2)
ax = by_place["miss_pct"].sort_values().plot(kind="barh",
figsize=(7, 4))
ax.set_title("Forest miss as a share of district value")
ax.set_xlabel("Average miss / average value")
ax.set_ylabel("Location")
plt.show()
top = res["actual"] >= 400000
print(round(res.loc[top, "bias"].mean()))
print(round(res.loc[~top, "bias"].mean()))
import os
os.makedirs("output/pandas", exist_ok=True)
path = "output/pandas/l64_predictions.csv"
res.round(0).to_csv(path)
print(pd.read_csv(path, index_col=0).shape)
gain = 1 - forest_mae / base_mae
print(f"Forest misses by {forest_mae:,.0f} on average,")
print(f"{gain:.0%} smaller than guessing the median.")
Recap#
- Look at the target first: capped values distort a model
- Ratios beat raw totals for comparing districts
- get_dummies turns text categories into 0/1 columns
- Split first, then fill gaps using training data only
- Always compare a model's error with a simple baseline
Challenges#
- Add income_per_person as a feature. Does the forest improve?
- Group the forest's misses by housing_median_age bands.
- Refit without latitude and longitude. How much worse is it?
What's next#
Lesson 65: Capstone Project - Sales Analytics with Pandas One real retail dataset, taken from raw file to finished insights.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



