SproutStackSproutStack home

Messy Data: Missing Values & Categories

5 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

The unglamorous 80%

Ask practitioners where their time goes and the answer is unanimous: not modeling — cleaning. Real tables have blanks, "N/A" strings, cities spelled three ways, and income in mixed currencies. Models eat numbers, so every non-number must be converted and every gap filled deliberately. This chapter is that craft.

Missing values: fill thoughtfully

  • Numbers: median imputation is the safe default (robust to outliers, unlike means). Deleting rows is only okay when gaps are few and random — otherwise you bias the dataset toward whoever fills forms completely.
  • Categories: a "Missing" category of its own often outperforms fancy imputation — missingness itself carries signal (people who skip "income" differ from those who answer).
  • Never: magic constants like 99999, which the model reads as a real, enormous value.

Categories to numbers

Models multiply; words don't multiply. One-hot encoding (a column per city, 0/1) works for a handful of values. Hundreds of cities? One-hot explodes dimensionality — switch to ordinal (only if order is real), frequency, or target encoding. And scale numeric ranges for distance-based models, or income will drown out visit counts.

import pandas as pd
df = df.fillna({"age": df["age"].median()})
df = pd.get_dummies(df, columns=["city"], drop_first=True)

A worked cleanup

A sign-up table arrives like this: age has blanks, city contains "NYC", "New York", and "new york ", income holds strings like "$52,000", and signup_source sometimes says "N/A".

  1. Standardize text. Trim spaces, lowercase, and map known variants to one value, so the three spellings become "new york".
  2. Parse numbers. Strip "$" and "," from income and convert to a number; anything that still fails to parse becomes a real missing value.
  3. Make missing values explicit. Turn "N/A", empty strings, and similar markers into proper missing values, so every tool recognizes them.
  4. Impute, and keep a flag. Fill missing ages with the training median, and add an age_missing column (1 or 0) so the model can still learn whether skipping the question meant something.
  5. Encode categories. One-hot encode city if there are only a few, or use a frequency or target encoding if there are hundreds.

Outliers: error or extreme?

Run df.describe() and look at the minimum and maximum of each column. An age of 250 is a data-entry error: fix it or mark it missing. A very high income may be perfectly real. Do not delete genuine extremes just because they are inconvenient. For heavily skewed values like income, capping at a sensible percentile or taking the logarithm often helps models more than deletion does.

Let a pipeline remember the steps

Cleaning steps applied by hand in a notebook are easy to forget when new data arrives. scikit-learn's ColumnTransformer and Pipeline bundle imputing, encoding, and scaling with the model, fitted on the training split and applied identically to everything after.

The golden rule: fit on train, apply everywhere

Fit imputers, encoders, and scalers on train only, then transform validation/test with those frozen parameters. Fitting on full data leaks test information into training — the quietest, commonest form of cheating in ML.

Remember this

  • Median for numbers, explicit "Missing" for categories, one-hot for few, encodings for many.
  • Fit preprocessing on train only. Clean data beats fancy models, every time.

Check your understanding

5 questions · first-try answers earn the most XP

1. Why is median imputation a safer default than mean imputation for missing numbers?
2. Why is filling a missing number with a sentinel like 99999 a bad idea?
3. When can deleting rows with missing values be acceptable?
4. A categorical column has 300 distinct city names. Why does one-hot encoding become a problem?
5. Why must imputers, encoders and scalers be fitted on the training split only?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

End of Data First

Take the section checkpoint

A short mixed quiz on all 3 chapters, to check you are ready to move on.

Related chapters

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.