Ir para o conteúdo

Lição 8 · Missing Values

Filling or Dropping Missing Values

Decide whether to keep, drop or fill missing values. Compare mean, median, group and forward fill imputation, add flags and avoid leaking information.

You found the gaps and thought about why they exist. Now you can choose what to do. There are three broad options: leave them missing, drop records or columns, or impute, which means fill in estimated values. No option is correct everywhere.

Option 1: leave them missing

This is often a good choice. Many tools can skip missing values in calculations, and "unknown" is honest. You can also make it a category of its own, such as region = "Not recorded", so totals still add up.

Option 2: drop

  • Drop rows when a row is useless without that value, for example an order line with no product that cannot be traced. Dropping every row with any gap can remove a large share of the data and bias what remains.
  • Drop columns that are almost entirely empty and not needed. Check first: a mostly empty cancellation_reason is expected if few orders are canceled.

Option 3: impute

Method Idea Watch out
Constant Fill with a known meaning, such as 0 Only if absence really means that
Mean or median One typical value Shrinks the spread
Mode Most frequent category Inflates the common category
Group median Typical value for similar records Small groups are unreliable
Forward fill Repeat the previous value in time order Wrong across long gaps
Interpolation Estimate between neighbors Assumes smooth change
Model-based or multiple imputation Predict from other columns Needs care and expertise

Multiple imputation creates several plausible filled datasets, analyzes each and combines the results, so the uncertainty from guessing is not hidden. A single filled value looks exactly as certain as a measured one.

Compare the effects

Python Compare imputation methods

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

One large value (300) drags the mean upward, so mean filling invents values far above anyone in the junior group. The median resists extremes. The group median uses what you know about each record. Compare the spread column too: filling gaps with central values tends to make data look less varied.

Keep a flag

Add an indicator column before filling. Anyone using the data can then see which values are real.

Python pandas: flag, then fill by group

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

We kept the original score column and wrote the result to a new one. If a whole group has no known values, its median is missing too, so check again after filling.

Time series

For values that stay the same until they change, such as a price list, forward fill can be right. For measurements that change constantly, a long forward fill invents a flat line. Set a limit.

Python Forward fill with a limit

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sort by time first, and fill within each sensor or account, so one device's value never flows into another's rows.

Imputation and machine learning

If you will train a model, compute fill values from the training data only, then apply them to validation and test data. Using all rows lets information from the test set leak into training and can make results look better than they are.

A decision guide

  1. Does the gap have a known meaning? Fill that meaning.
  2. Can you recover the true value from a source? Recover it.
  3. Does your analysis work with missing values? Leave them.
  4. Is the row unusable for this question? Exclude it, count it and check who was excluded.
  5. Must you estimate? Choose a method that fits the reason, add a flag and compare results with and without it.

Common mistake: imputing identifiers, outcomes or legally important fields. Never invent an email address, a diagnosis or a signature date.

Check what dropping removes

Before you drop rows, compare the rows you would remove with the rows you would keep. Do they come from the same sources, periods and customer groups? If 30% of the rows from one region disappear and only 2% elsewhere, your cleaned data now tells a different story about the regions. Print this comparison every time, because it takes only a few lines of code.

Also think about columns together. Each column may be only a little incomplete, yet requiring all of them to be filled can remove many rows, since the gaps fall in different places. Require only the columns that the current question needs.

Document the method

For every imputed column, record the method, the groups used, the number of filled values and the date of the run. If you change the method later, results can change even though the raw data did not, and this record explains why.

Compare results

A simple and honest test is to run the main calculation twice: once with the missing values excluded and once with them filled. If both versions lead to the same decision, say so. If they differ in a way that matters, show both and explain what each assumes. Do not pick the version that supports the answer you hoped for.

Do not fill too early

Keep the cleaned table honest, with real gaps and flags. Apply imputation in the analysis that needs it. Different questions may call for different methods, and a filled source table forces one choice on everyone.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What does filling many gaps with one mean value usually do to a column?

    Many identical central values make the data look less variable than it is.
  2. 2. Why add a was_missing flag?

    The flag keeps the information so others can check or exclude estimated values.
  3. 3. Where should fill values for a predictive model come from?

    Using test data to compute fill values leaks information into training.

Summary

  • Leaving values missing is often valid.
  • Drop only with a reason, and check what you lose.
  • Pick imputation to match the cause, and keep flags.
  • Limit time-series filling and avoid leakage.

Next: Removing Exact Duplicates

Seu progresso fica salvo neste navegador. Não precisa de conta.