Skip to the workspace
Pebellslearn by building
Cleaning Data  ›  Lesson

Dropping, Imputing and Filling Gaps

Dropping vs. Imputing 15 minMissing values can be dropped, imputed with a reasoned value such as the median or a label, or filled from a neighbour when row order carries meaning.

python data analysis / Dropping, Imputing and Filling Gaps

Explore each scene at your own pace.

01 · The rule

The rule

Dropping, Imputing and Filling Gaps

You found four missing cells in the raw export. Now you must decide what to do with each. Drop the row, fill in a sensible value, or copy a neighbour's value? Each choice changes your final numbers, so the choice should be deliberate, not a habit.

The rule

Drop what you cannot trust, fill what you can reason about.

Three tools, using raw from the last lesson (gaps: copies in rows 2 and 6, genre in row 3, price in row 4).

Drop removes rows (or columns) with gaps:

raw.dropna()                    # any gap: 4 rows left
raw.dropna(subset=["copies"])   # only if copies is missing: 6 rows left
raw.dropna(axis=1)              # drop columns with any gap instead

Impute replaces a gap with a chosen value, often a summary of the column:

raw["copies"].fillna(raw["copies"].median())  # median of known values is 3.5
raw["genre"].fillna("unknown")                # a clear label for text

Forward / backward fill copies a neighbour. This fits ordered data, like a daily reading that carries on until it changes:

raw["copies"].ffill()   # row 2 takes row 1's 5; row 6 takes row 5's 6
raw["copies"].bfill()   # row 2 takes row 3's 4; row 6 takes row 7's 3

Each method returns a new Series or DataFrame; assign it back to keep it: raw["genre"] = raw["genre"].fillna("unknown").

How to choose:

  • Drop when few rows are affected and they are missing at random, or the missing field is essential (a sale with no price cannot count toward revenue).
  • Impute with the median for skewed numbers, the mean for balanced ones, and an explicit label for categories.
  • Fill forward/backward only when the order of rows means something, such as time.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.