PY-401 ยท Cleaning messy data
Missing values
โฑ 9 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
Missing values are empty cells, which pandas shows as NaN (or None for text). df.isna().sum() counts them per column, df.dropna() removes rows that have any, and df["col"].fillna(value) fills them in. Decide per column: drop the row, fill with a sensible value such as the mean, or mark it as "Unknown".
- Count missing values per column
- Drop rows with dropna
- Fill gaps with fillna
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import numpy as npimport pandas as pdsales = pd.DataFrame({"store": ["Pune", "Leeds", "Oslo", "Lyon"],"units": [12, np.nan, 9, 15],"manager": ["Asha", "Ben", None, "Dina"],})print(sales.isna().sum())print(sales.dropna())sales["units"] = sales["units"].fillna(sales["units"].mean())sales["manager"] = sales["manager"].fillna("Unknown")print(sales)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
store 0
units 1
manager 1
dtype: int64
store units manager
0 Pune 12.0 Asha
3 Lyon 15.0 Dina
store units manager
0 Pune 12.0 Asha
1 Leeds 12.0 Ben
2 Oslo 9.0 Unknown
3 Lyon 15.0 Dina ๐ฏ scores has gaps. Fill missing "marks" with 0, then drop any row that is still missing a "name". Store the result in clean.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
clean = scores.copy(); clean["marks"] = clean["marks"].fillna(0); clean = clean.dropna(subset=["name"])
- The problemA store export has 4 rows, but Leeds forgot to send its units and nobody filled in Oslo's manager. Average the units now and the empty cell quietly changes the answer.
- The Python idea
df.isna().sum()Missing values are empty cells, which pandas shows asNaN(orNonefor text). - In real lifeA hospital dashboard fills missing heart-rate readings with the patient's previous reading (
ffill()) instead of the ward average, because a gap of one minute means "probably unchanged".
Start with a question
A store export has 4 rows, but Leeds forgot to send its units and nobody filled in Oslo's manager. Average the units now and the empty cell quietly changes the answer.
Real data always has gaps. Ignoring them gives wrong totals and averages, and many machine-learning tools refuse to run with NaN in the data.
Explain it like I'm 10
Missing values are blank boxes on a worksheet. Before you add up the answers, you either cross out the rows with blanks or write your best guess in each blank.
The technical explanation
NaN means "not a number" and marks a missing value. In text columns pandas may show None. isna() finds both.
df.isna().sum() is the first thing to run on a new file: one count per column.
df.dropna() drops every row with any gap. df.dropna(subset=["units"]) only looks at the columns you name.
fillna fills gaps: a fixed value such as 0 or "Unknown", or a statistic such as df["units"].mean(). Assign the result back to the column.
Syntax
df.isna().sum()
df.dropna(subset=["col"])
df["col"] = df["col"].fillna(value) Real-world scenario
A hospital dashboard fills missing heart-rate readings with the patient's previous reading (ffill()) instead of the ward average, because a gap of one minute means "probably unchanged".
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Fixing types and dates โQuestions people ask
Should I drop or fill missing values in pandas?
Drop rows when only a few are missing and they are not special. Fill when dropping would lose too much data: use 0 or "Unknown" when that is the true meaning, the mean or median for numbers, or the previous value for readings over time.
What is the difference between NaN and None in pandas?
NaN is a floating-point marker for a missing number; None is Python's empty value and often appears in text columns. pandas treats both as missing, so isna, dropna and fillna handle them the same way.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner Should I drop or fill missing values in pandas?
Drop rows when only a few are missing and they are not special. Fill when dropping would lose too much data: use 0 or "Unknown" when that is the true meaning, the mean or median for numbers, or the previous value for readings over time.
beginner What is the difference between NaN and None in pandas?
NaN is a floating-point marker for a missing number; None is Python's empty value and often appears in text columns. pandas treats both as missing, so isna, dropna and fillna handle them the same way.
intermediate How do you count missing values in each column?
df.isna().sum(). isna marks gaps as True, and sum counts the Trues per column.
intermediate What does df.dropna() do with no arguments?
Drops every row that has any missing value. Any gap in a row removes that row.
Quick revision
Remember
- Count missing values per column
- Drop rows with dropna
- Fill gaps with fillna
dropna()with no arguments drops a row if any column is empty, which can throw away most of your data. Usesubset=["units"]to drop only rows missing the columns you need.
Syntax
df.isna().sum()
df.dropna(subset=["col"])
df["col"] = df["col"].fillna(value) Official documentation
- Working with missing data (docs.python.org)