Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathPrepare Data for a Machine Learning Model
  1. 1
    Train-Test Split and Data Leakage: Split First, Learn After
  2. 2
    Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  3. 3
    Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  4. 4
    Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  5. 5
    Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  6. 6
    Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  7. 7
    Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Data Preprocessing

Learning path: Prepare Data for a Machine Learning Model · Step 7 of 7

Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data

A hands-on project: take the raw weatherAUS.csv through a health check, a new Month column, leak removal, a stratified split and a two-lane ColumnTransformer. 22 columns become 127 numeric inputs with zero blanks, and a 0.776 baseline to beat.

Chaand Sheikh

·27 November 2026Data Preprocessing

What you will learn

  • Run a health check: shape, class balance and the share of blanks
  • Make a Month column from Date, and remove the leak and the id
  • Build a two-lane ColumnTransformer, fit it on the train rows and transform both sets
  • Explain where the 127 model inputs come from, and compute the baseline to beat

Before you start

  • Pipelines and ColumnTransformer
  • Encoding Categorical Data
  • Train-Test Split and Data Leakage

Think about a restaurant kitchen. Food arrives from the supplier muddy, uneven, and with some of it missing. Before service, the prep station washes it, chops it and portions it. Only then does the chef cook, and because the food is ready, cooking is fast.

Preprocessing is that prep station, and the model is the chef. In this project you'll take the raw Rain in Australia table (will it rain tomorrow?) and get it ready for a model, using everything from this section:

  • Washing is filling the blanks, with SimpleImputer.
  • Chopping is putting the numbers on the same scale, with StandardScaler.
  • Portioning is turning text into number columns, with OneHotEncoder.

And one rule from the whole section: write the prep recipe from the train rows only, then use the same recipe on the test rows. Nothing in this project trains a model yet.

The brief

Try it on your own first. Starting from weatherAUS.csv:

  1. Health check: print the shape, the class balance of RainTomorrow, and the three columns with the most missing values.
  2. New column: create a Month column (as text) from Date.
  3. Leaks and ids: build X without Date, RISK_MM and RainTomorrow. Why does RISK_MM go?
  4. Split first: test_size=0.2, stratify=y, random_state=42.
  5. Two lanes: numbers get a median imputer and StandardScaler; text gets a most-frequent imputer and OneHotEncoder(handle_unknown="ignore"), joined in a ColumnTransformer.
  6. Fit on train, transform both: print both shapes and check no values are missing. Bonus: how many columns did each text column turn into?
  7. Baseline: what accuracy does always predicting "No" give on the test set?

The rest of this article is the worked solution, step by step.

The project in five steps 1. Healthcheck 2. Monthfrom Date 3. Dropleak and id 4. Split80/20 5. Fit ontrain only raw CSV: 142,193 rows, 24 columns out: 127 numeric columns, 0 blanks
The project in order. Nothing learns from the data before step 4, the split.

Step 1: Health check

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import (
    StandardScaler, OneHotEncoder)

One cell, three checks: the shape, the balance of the answer, and the share of blanks per column.

df = pd.read_csv("weatherAUS.csv")
print(df.shape)
rain = df["RainTomorrow"]
share = rain.value_counts(normalize=True)
print(share.round(3).to_dict())
blank = df.isnull().mean()
print(blank.nlargest(3).round(3).to_dict())
(142193, 24)
{'No': 0.776, 'Yes': 0.224}
{'Sunshine': 0.477, 'Evaporation': 0.428, 'Cloud3pm': 0.402}

142,193 rows and 24 columns. About 78% of days are No and only 22% are Yes, so the classes are imbalanced: remember that. And Sunshine is blank in 47.7% of the rows, with Evaporation and Cloud3pm close behind. We already know how to fill these (see Handling Missing Data).

Step 2: A new column from an old one

Sometimes the best column is one you make yourself. Date has 3,436 different values, which makes it basically an id, and a model can't learn from an id. Its month has only 12 values and tells you the season. (Encoding Categorical Data counts both.)

# Date is an id, but its month carries the season
dates = pd.to_datetime(df["Date"])
df["Month"] = dates.dt.month.astype(str)
print(df[["Date", "Month"]].head(3))
         Date Month
0  2008-12-01    12
1  2008-12-02    12
2  2008-12-03    12

pd.to_datetime turns the text into real dates, .dt.month picks out the month number, and .astype(str) makes it text so it's treated as a category, not as a size. Month 12 isn't "bigger" than month 1.

Step 3: Remove the leak and the id

# RISK_MM is tomorrow's rain: it leaks the answer
drop_cols = ["Date", "RISK_MM", "RainTomorrow"]
X = df.drop(columns=drop_cols)
y = df["RainTomorrow"]
print(X.shape)
(142193, 22)

RISK_MM is the amount of rain that falls tomorrow, so it already contains the answer. That's a leak and it has to go (Train-Test Split and Data Leakage shows a tree scoring 1.0 on it alone). Date goes because we kept its month. That leaves 22 feature columns in X, and the label alone in y.

Step 4: Split first

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(113754, 22) (28439, 22)

20% of the rows are kept back for testing. stratify=y keeps the rain/no-rain balance the same in both parts, and random_state=42 gives everyone the same split.

Step 5: Two lanes

num_cols = X.select_dtypes("number").columns
cat_cols = X.select_dtypes(exclude="number").columns
print(len(num_cols), len(cat_cols))
print(*cat_cols)
16 6
Location WindGustDir WindDir9am WindDir3pm RainToday Month

16 number columns and 6 text columns. Month is in the text list on purpose, because we made it as text. Now the lanes, exactly as in Pipelines and ColumnTransformer:

num_lane = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler())])
cat_lane = Pipeline([
    ("impute", SimpleImputer(strategy="most_frequent")),
    ("onehot", OneHotEncoder(handle_unknown="ignore"))])
preprocess = ColumnTransformer([
    ("num", num_lane, num_cols),
    ("cat", cat_lane, cat_cols)])

Step 6: Fit on train, transform both

The most important step. fit_transform on the train rows learns the medians, means, spreads and categories, then changes the train table. transform on the test rows uses the very same learned values and learns nothing new.

Xt_train = preprocess.fit_transform(X_train)
Xt_test = preprocess.transform(X_test)
print(Xt_train.shape, Xt_test.shape)
(113754, 127) (28439, 127)

Both sets now have 127 columns. Check for blanks, and look at the first and last column names:

import numpy as np
dense = Xt_train.toarray()
print("missing after:", int(np.isnan(dense).sum()))
names = preprocess.get_feature_names_out()
print(names[:2])
print(names[-2:])
missing after: 0
['num__MinTemp' 'num__MaxTemp']
['cat__Month_8' 'cat__Month_9']

Zero missing values. The result is a sparse matrix (mostly zeros from one-hot), so .toarray() turns it into a normal array for the check. The names show where each column came from: num__ for the number lane and cat__ for the text lane.

Where do the 127 columns come from?

cat = preprocess.named_transformers_["cat"]
sizes = cat["onehot"].categories_
print({c: len(k) for c, k in zip(cat_cols, sizes)})
{'Location': 49, 'WindGustDir': 16, 'WindDir9am': 16, 'WindDir3pm': 16, 'RainToday': 2, 'Month': 12}
Where the 127 columns come from 16 49 16 16 16 12 numbers Location WindGustDir WindDir9am WindDir3pm RainToday 2 Month 16 number columns stay 16. 6 text columns become 49 + 16 + 16 + 16 + 2 + 12 = 111. 16 + 111 = 127 model inputs, every one of them a number.
Each number column stays one column; each text column becomes one column per category it saw in the train rows.

Each number column stays one column: 16. Each text column becomes one column per category: Location 49, the three wind directions 16 each, RainToday 2, Month 12. That's 111. So 16 + 111 = 127. Twenty-two raw columns became 127 model inputs.

Step 7: The baseline to beat

One last number before any model: what if you always predict "No"?

print(round((y_test == "No").mean(), 3))
0.776

Guessing "No" every time is already right 77.6% of the time. That's the baseline. A real model has to beat 0.776, or it hasn't learned anything useful. This is why the health check flagged the imbalance.

Common mistakes

  • Keeping RISK_MM. Any score you get with it is fake.
  • Making Month a number. Without .astype(str) it lands in the number lane and gets scaled like a size, as if December were "more" than January.
  • Fitting preprocess before the split, or calling fit_transform on X_test.
  • Judging accuracy without a baseline. 0.776 sounds good until you see it's what "always No" gets.

Quick recap

StepWhat you didResult
Health checkshape, balance, blanks142,193 x 24; 77.6% No; Sunshine 47.7% blank
New columnMonth from Date, as text12 values instead of 3,436
Leak and iddrop RISK_MM and Date22 feature columns
Split first80/20, stratified113,754 train, 28,439 test
Two lanes, fit on trainColumnTransformer127 columns, 0 blanks
Baselinealways "No"0.776

Try it yourself

Make a Day column from the date, as a number (dates.dt.day), and add it to X. Which lane does it go to, and how many model inputs do you get now?

The starter notebook (with the same steps as to-dos), the finished notebook and the dataset are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Train-Test Split and Data Leakage: Split First, Learn After

Why the train-test split comes before everything else: an 80/20 split with stratify and random_state, a scaler that leaks test rows, and a column that secretly holds the answer. Shown on Rain in Australia.

Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer

Count the blanks with isnull().sum(), see why dropna() would throw away 60% of the rows, and fill the gaps with SimpleImputer: median for numbers, most frequent for text, learned from the train rows only. Shown on Rain in Australia.

Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder

Models only understand numbers. Encode T-shirt sizes with OrdinalEncoder, colours with OneHotEncoder, avoid the dummy variable trap, handle a colour the encoder never saw, tame a date with 3,436 values, and encode the answer with LabelEncoder.

Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care

Put features on the same scale so each one gets a fair say. StandardScaler and MinMaxScaler fitted on the train rows, the formula checked by hand, and a wine test where KNN jumps from 0.806 to 0.972 while a decision tree stays at 0.944.

On this page
  • The brief
  • Step 1: Health check
  • Step 2: A new column from an old one
  • Step 3: Remove the leak and the id
  • Step 4: Split first
  • Step 5: Two lanes
  • Step 6: Fit on train, transform both
  • Where do the 127 columns come from?
  • Step 7: The baseline to beat
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.