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 2 of 7

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.

Chaand Sheikh

·27 November 2026Data Preprocessing

What you will learn

  • Count the blanks in every column with isnull().sum()
  • Explain why dropna() can cost most of your rows
  • Fill numbers with the median and text with the most frequent value using SimpleImputer
  • Fit the imputer on the train rows only and read what it learned in statistics_

Before you start

  • Reading a CSV with pandas
  • Train-Test Split and Data Leakage

Think about a paper survey. Five people fill it in, but Ben, Dan and Ella skip one question. What do you do with those forms?

Option A: throw away every form with a blank. Only two forms are left, and you lose most of the answers.

Option B: fill each blank with a good guess, like the most common answer. All five forms are kept.

Missing data in machine learning is exactly this choice: drop, or fill. A model can't train on blanks, so you deal with them before the model sees the data. In this lesson you'll count the blanks in the Rain in Australia weather table, see what dropping would cost, and fill the gaps with scikit-learn's SimpleImputer.

Split first, then count the blanks

As always, the split comes first, so the test rows stay untouched. Everything we learn from now on comes from the train rows only. (If that rule is new to you, read Train-Test Split and Data Leakage first.)

import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv("weatherAUS.csv")
X = df.drop(columns=["Date", "RISK_MM", "RainTomorrow"])
y = df["RainTomorrow"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)

Now count. isnull() gives True or False for every single value, and sum() adds up the Trues in each column.

missing = X_train.isnull().sum()
print(missing.sort_values(ascending=False).head(4))
Sunshine       54344
Evaporation    48695
Cloud3pm       45669
Cloud9am       42877
dtype: int64

Sunshine is missing 54,344 times in the train rows. Evaporation and the two cloud columns are close behind. These aren't a few stray gaps.

What if we drop every row with a blank?

That's option A. dropna() removes every row that has even one blank.

complete = X_train.dropna()
print(X_train.shape, complete.shape)
print(f"{len(complete) / len(X_train):.0%} complete")
(113754, 21) (45121, 21)
40% complete
dropna keeps only 40% of the train rows X_train 113,754 rows dropna() 45,121 kept 60% thrown away Only 40% of the rows have no blank at all, so dropping costs far too much. We fill instead.
Dropping every row with a blank keeps 45,121 of 113,754 train rows: 40%.

We started with 113,754 rows and only 45,121 are complete. Dropping would throw away 60% of our data. That's far too much, so we fill instead.

Fill with what? Look at Rainfall

The obvious guess is the mean. Let's check it on the rainfall column:

rain = X_train["Rainfall"].dropna()
print(round(rain.mean(), 2), rain.median())
print(f"{(rain == 0).mean():.0%} of days are dry")
2.36 0.0
64% of days are dry

64% of days are dry, zero millimetres. A few big storms pull the mean up to 2.36 mm, but the median, the middle day, is 0. If you fill a blank with 2.36, you invent drizzle on what was most likely a dry day.

When a few big values drag the mean up, fill with the median. The median doesn't care how big the storms are.

SimpleImputer: fit learns, transform fills

SimpleImputer does the filling in two steps:

fit on X_train, transform X_train and X_test X_train with blanks SimpleImputer MinTemp 12.0 Evaporation 4.8 1. fit X_train 0 blanks X_test with blanks X_test 0 blanks 2. transform both, same values never fitted
The imputer learns its fill values from the train rows only, then uses those same values to fill the train rows and the test rows.
  1. fit looks at the train rows and learns one fill value per column.
  2. transform fills every blank with the value learned for its column, in the train rows and in the test rows.

Learn from train, fill everywhere. It's the same fit-on-train, transform-both rule as every other preprocessing step.

Numbers: the median

First pick the number columns, create the imputer with strategy="median", and fit it on X_train:

from sklearn.impute import SimpleImputer
num = X_train.select_dtypes(include="number").columns
num_imputer = SimpleImputer(strategy="median")
num_imputer.fit(X_train[num])
SimpleImputer(strategy='median')

Then transform both sets and count the blanks again:

X_train_num = num_imputer.transform(X_train[num])
X_test_num = num_imputer.transform(X_test[num])
print(pd.isnull(X_train_num).sum())
print(pd.isnull(X_test_num).sum())
0
0

Zero blanks in both.

What the imputer learned

The median of each column is stored in statistics_, one value per column:

stats = pd.Series(num_imputer.statistics_, index=num)
print(stats.head(4))
MinTemp        12.0
MaxTemp        22.6
Rainfall        0.0
Evaporation     4.8
dtype: float64

Rainfall is 0.0, the median we just saw. Evaporation is 4.8. Notice the trailing underscore: anything a scikit-learn object learns during fit ends with _. You set strategy; fit learns statistics_.

Text: the most frequent value

Text has no middle value, so for text columns use strategy="most_frequent". Same two steps.

cat = X_train.select_dtypes(exclude="number").columns
cat_imputer = SimpleImputer(strategy="most_frequent")
cat_imputer.fit(X_train[cat])
print(pd.Series(cat_imputer.statistics_, index=cat))
Location       Canberra
WindGustDir           W
WindDir9am            N
WindDir3pm           SE
RainToday            No
dtype: str

The most common location in the train rows is Canberra, and RainToday is mostly No. Transform both sets:

X_train_cat = cat_imputer.transform(X_train[cat])
X_test_cat = cat_imputer.transform(X_test[cat])
print(pd.isnull(X_train_cat).sum())
print(pd.isnull(X_test_cat).sum())
0
0

The text blanks are gone too.

Which one when?

SituationWhat to do
Very few rows have a blank, or the label itself is blankDrop those rows
A column is almost completely emptyDrop the column
Skewed numbers (like Rainfall)Fill with the median
Symmetric numbersThe mean is fine
TextThe most frequent value, or a label such as "missing"

Whatever you choose, fit it on the train rows only.

Common mistakes

  • Calling dropna() without checking the cost. Here it would keep only 40% of the rows.
  • Filling skewed numbers with the mean. 2.36 mm of rain on a dry day is an invented value.
  • Fitting the imputer on all rows, or calling fit on X_test. The test rows only get transform.
  • Using the median strategy on text columns. Text needs most_frequent (or a constant).

Quick recap

StepCodeRain in Australia
Count the blanksX_train.isnull().sum()Sunshine: 54,344 blanks
Cost of droppingX_train.dropna()45,121 of 113,754 rows, 40%
Fill numbersSimpleImputer(strategy="median")Rainfall 0.0, Evaporation 4.8
Fill textSimpleImputer(strategy="most_frequent")Location Canberra, RainToday No
Fit on train onlyfit(X_train), transform both0 blanks in train and test

Try it yourself

Fill the numbers with strategy="mean" instead of the median. How does the value learned for Rainfall change in statistics_?

The 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
Train-Test Split and Data Leakage: Split First, Learn After
Next →
Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
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.

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.

Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object

Pack imputing, encoding, scaling and the model into one scikit-learn Pipeline with two ColumnTransformer lanes. One fit on the train rows, 21 columns in, 115 out, 0.849 test accuracy, and a raw row with a blank predicted directly.

On this page
  • Split first, then count the blanks
  • What if we drop every row with a blank?
  • Fill with what? Look at Rainfall
  • SimpleImputer: fit learns, transform fills
  • Numbers: the median
  • What the imputer learned
  • Text: the most frequent value
  • Which one when?
  • 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.