Skip to content
Codescope

Missing data & NaN

A gap is a value. Deciding what it means is your job, not pandas'.

core9 min7 steps

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
Rownamescorefloat64cityobject
0Ana80north
1BenNaNsouth
2Cal60NaN
3DeeNaNNaN
4Eli100east

df.isna().sum()

Rowmissing
name0
score2
city2

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.

01 / 07

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.

analysis.pyPython
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