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.
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
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 looks at the train rows and learns one fill value per column.
- 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?
| Situation | What to do |
|---|---|
| Very few rows have a blank, or the label itself is blank | Drop those rows |
| A column is almost completely empty | Drop the column |
| Skewed numbers (like Rainfall) | Fill with the median |
| Symmetric numbers | The mean is fine |
| Text | The 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
fitonX_test. The test rows only gettransform. - Using the median strategy on text columns. Text needs
most_frequent(or a constant).
Quick recap
| Step | Code | Rain in Australia |
|---|---|---|
| Count the blanks | X_train.isnull().sum() | Sunshine: 54,344 blanks |
| Cost of dropping | X_train.dropna() | 45,121 of 113,754 rows, 40% |
| Fill numbers | SimpleImputer(strategy="median") | Rainfall 0.0, Evaporation 4.8 |
| Fill text | SimpleImputer(strategy="most_frequent") | Location Canberra, RainToday No |
| Fit on train only | fit(X_train), transform both | 0 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 →Train-Test Split and Data Leakage: Split First, Learn After
Next →Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
StudyEasy AI Community
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
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.