This lab explores the California Housing dataset with pandas, matplotlib and seaborn. It is the exploratory step you do before training a scikit-learn regression model. The notebook above loads the Kaggle CSV, checks its shape, drops rows with missing values, summarises the numeric columns and starts plotting relationships. Below you will find setup steps, an explanation of each output, the full set of plots, and a scikit-learn pipeline that turns the exploration into a baseline model.
Set up the environment and get the dataset
The notebook reads datasets/housing.csv from a folder next to the notebook, but it never shows how to get that file. Create an isolated Python environment, install the libraries, then download the CSV from Kaggle, either through the website or with the Kaggle CLI.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install pandas matplotlib seaborn scikit-learn jupyterlab kaggle
# Needs a Kaggle API token in ~/.kaggle/kaggle.json
mkdir -p datasets
kaggle datasets download -d camnugent/california-housing-prices -p datasets --unzip
ls datasets
# housing.csv
jupyter labCode language: PHP (php)
Note: If you can't use Kaggle, sklearn.datasets.fetch_california_housing(as_frame=True) downloads a related version of the dataset. It is not the same file: it has 8 engineered features (such as AveRooms and AveOccup), no ocean_proximity column and no missing values, and its target MedHouseVal is measured in units of $100,000. The code on this page assumes the Kaggle CSV.
What the columns mean
Each row is one census block group in California, not one house. That explains why total_rooms and population take values in the thousands.
| Column | Meaning | Things to watch |
|---|---|---|
| longitude, latitude | Location of the block group | Strong geographic patterns near the coast |
| housing_median_age | Median age of houses | Capped at 52 (see the max in describe()) |
| total_rooms, total_bedrooms | Totals for the whole block group | Divide by households to get per-home values |
| population, households | People and households in the block | Heavily right-skewed |
| median_income | Median household income | Scaled: 3.87 means roughly $38,700; capped near 15 |
| median_house_value | Target variable in USD | Capped at 500,001 |
| ocean_proximity | Categorical location label | Text, so it must be encoded before modelling |
Reading the output of the steps above
housing_data.shapereturns(20640, 10): 20,640 rows and 10 columns.- After
dropna()the shape is(20433, 10), so 207 rows were removed. All of them are missingtotal_bedrooms. You can confirm this withhousing_data.isna().sum()before dropping. describe()lists only the 9 numeric columns.ocean_proximityis text, so it is left out. Usehousing_data.describe(include='object')orvalue_counts()to summarise it.- The
maxofmedian_house_valueis exactly 500001 andhousing_median_agetops out at 52. Both values were capped when the data was collected. A model can't learn anything above these limits, so decide whether to keep or remove those rows. total_roomshas a mean of about 2,636 but a max of 39,320. Large gaps like this between the 75% quartile and the max point to outliers and skewed distributions.unique()onocean_proximityreturns five categories.ISLANDcovers only a handful of rows (five in the full file), which matters if you stratify or split by this column.
housing_data.isna().sum()
housing_data['ocean_proximity'].value_counts()
(housing_data['median_house_value'] >= 500001).sum() # how many capped targetsCode language: PHP (php)
Visualizing relationships
The notebook stops after its first plot of median house value. The cells below cover the views that matter most for this dataset. Run them after the cleaning cells above.
# 1. Distribution of every numeric column
housing_data.hist(bins=50, figsize=(14, 10))
plt.tight_layout()
plt.show()
# 2. Income vs house value: the strongest single predictor
fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(data=housing_data, x='median_income', y='median_house_value', alpha=0.2, ax=ax)
ax.set_xlabel('Median income (tens of thousands USD)')
ax.set_ylabel('Median house value')
plt.show()
# 3. House value by ocean proximity
plt.figure(figsize=(10, 6))
sns.boxplot(data=housing_data, x='ocean_proximity', y='median_house_value')
plt.show()
# 4. Geographic view: colour = value, size = population
housing_data.plot(kind='scatter', x='longitude', y='latitude', alpha=0.4,
s=housing_data['population'] / 100, c='median_house_value',
cmap='viridis', colorbar=True, figsize=(10, 7))
plt.show()
# 5. Correlation heatmap (numeric columns only)
corr = housing_data.corr(numeric_only=True)
plt.figure(figsize=(10, 8))
sns.heatmap(corr, annot=True, fmt='.2f', cmap='coolwarm')
plt.show()
corr['median_house_value'].sort_values(ascending=False)Code language: PHP (php)
Things to look for in these plots:
- A horizontal line of points at 500,001 in the income scatter plot. These are the capped values.
INLANDblock groups sitting much lower in the boxplot than coastal ones.- High-value clusters around the Bay Area and Los Angeles on the map.
median_incomeshowing the highest correlation with the target in the heatmap.
Adding more useful features
Totals per block group are hard to compare because blocks differ in size. Ratios usually tell you more about a typical home, and they often correlate better with the target than the raw totals do.
housing_data['rooms_per_household'] = housing_data['total_rooms'] / housing_data['households']
housing_data['bedrooms_per_room'] = housing_data['total_bedrooms'] / housing_data['total_rooms']
housing_data['population_per_household'] = housing_data['population'] / housing_data['households']
housing_data.corr(numeric_only=True)['median_house_value'].sort_values(ascending=False)Code language: PHP (php)
From exploration to a scikit-learn baseline
Exploration should tell you what preprocessing the model needs. For this dataset that means filling in missing bedrooms, scaling the numeric columns and one-hot encoding ocean_proximity. A Pipeline keeps those steps together, and because it is fitted only on the training split, test data can't leak into the preprocessing. This version imputes missing values instead of dropping rows, so it starts from the raw CSV.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
df = pd.read_csv('datasets/housing.csv')
X = df.drop(columns='median_house_value')
y = df['median_house_value']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
num_cols = X.select_dtypes(include='number').columns.tolist()
cat_cols = ['ocean_proximity']
preprocess = ColumnTransformer([
('num', Pipeline([
('impute', SimpleImputer(strategy='median')),
('scale', StandardScaler()),
]), num_cols),
('cat', OneHotEncoder(handle_unknown='ignore'), cat_cols),
])
model = Pipeline([('prep', preprocess), ('reg', LinearRegression())])
model.fit(X_train, y_train)
pred = model.predict(X_test)
print('MAE:', round(mean_absolute_error(y_test, pred)))
print('R2 :', round(r2_score(y_test, pred), 3))Code language: JavaScript (javascript)
A plain linear model leaves a large error on this data because the relationships are non-linear and the target is capped. Treat the scores as a baseline. To improve on it, swap LinearRegression for RandomForestRegressor or HistGradientBoostingRegressor and add the ratio features from the previous section.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
FileNotFoundError: datasets/housing.csv | The CSV isn't in a datasets folder next to the notebook | Download it as shown above, or pass an absolute path to read_csv |
ValueError: could not convert string to float: 'NEAR BAY' on corr() | Recent pandas versions no longer skip text columns silently | Use corr(numeric_only=True) |
Same error when calling model.fit | ocean_proximity was passed to the model as raw text | Encode it with OneHotEncoder in a ColumnTransformer |
Input X contains NaN | total_bedrooms has missing values | Use SimpleImputer or drop rows before fitting |
| No plot appears when running as a script | Outside Jupyter, figures aren't displayed automatically | Call plt.show() after each figure |
Corrections to the original notebook
- Run order: the execution counts jump around (24, 13–19, 51, 48), so the cells were run out of order. Use *Kernel → Restart and Run All* to check that the notebook works from top to bottom.
- Missing download step: the notebook reads
datasets/housing.csvbut never explains how to get it. Use the Kaggle download commands above. - Reproducibility:
housing_data.sample(5)returns different rows on every run. Usehousing_data.sample(5, random_state=42)to get the same output each time. - Silent data loss:
dropna()removes 207 rows without showing which column caused it. Inspectisna().sum()first. For modelling, prefer imputation inside a pipeline so you keep every row.
Frequently asked questions
Why does the California Housing dataset have missing values?
The Kaggle CSV has 207 rows with an empty total_bedrooms value. The scikit-learn version from fetch_california_housing has no missing values because it uses different, pre-computed features.
Why is median_house_value capped at 500,001?
Values above that level were capped when the data was collected, so the maximum shows up as exactly 500,001. Many tutorials remove these rows or flag them, because a model can't learn prices above the cap.
What is the difference between the Kaggle and scikit-learn California Housing datasets?
The Kaggle CSV has 10 raw columns, including totals and the text column ocean_proximity. The scikit-learn version has 8 per-household averages, no categorical column, and a target expressed in $100,000 units.
How do I use ocean_proximity in a scikit-learn model?
Encode it with OneHotEncoder inside a ColumnTransformer. This creates one binary column per category, and handle_unknown='ignore' keeps prediction from failing when a category was missing from the training split.
Which feature best predicts house value in this dataset?
median_income has the strongest correlation with median_house_value. Location features, meaning latitude, longitude and ocean proximity, add a lot of extra predictive power.
Related tutorials
- More Machine Learning tutorials
- Top 10 AI Pipeline Forecasting with ML Tools: Features, Pros, Cons & Comparison
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals