Missing data & NaN
A gap is a value. Deciding what it means is your job, not pandas'.
Before you start
Real data has gaps. A survey response is blank, a sensor was offline, a database field was NULL. Pandas represents these gaps with a special value: NaN ("not a number").
How you handle NaN is a design decision, not a technical one. Drop the rows? Fill with zero? Fill with the average? Each choice tells a different story — some are honest, some silently distort your answer.
This lesson shows the three common strategies (dropna, fillna, forward-fill) and points out the traps: e.g., sum() skips NaN silently, so a column that's mostly missing can produce a suspiciously small total.
df
NaN is a float value, not an empty cell| Row | name | scorefloat64 | cityobject |
|---|---|---|---|
| 0 | Ana | 80 | north |
| 1 | Ben | NaN | south |
| 2 | Cal | 60 | NaN |
| 3 | Dee | NaN | NaN |
| 4 | Eli | 100 | east |
df.isna().sum()
| Row | missing |
|---|---|
| name | 0 |
| score | 2 |
| city | 2 |
NaN is a floating-point value, which is why an int column with a gap becomes float64.
Step 1 of 7. Find the gaps before anything else. `isna()` returns a frame of booleans; summing it counts the missing values per column. Two scores and two cities are absent. Do this first, every time. Every later decision — drop, fill, or leave alone — depends on how much is missing and where.
Step 01 / 07
Find the gaps before anything else
isna() returns a frame of booleans; summing it counts the missing values per column. Two scores and two cities are absent.
Do this first, every time. Every later decision — drop, fill, or leave alone — depends on how much is missing and where.
import pandas as pdimport numpy as npdf.isna().sum() # count missing per columndf.dropna() # drop any row with a gapdf.dropna(subset=["score"]) # only care about one columndf["score"].fillna(0) # a constantdf["score"].fillna(df["score"].mean()) # the column meandf["score"].ffill() # carry the last value forwarddf["score"].mean() # skips NaN by defaultlen(df["score"]) # counts NaNdf["score"].count() # does not