2. Reading and inspecting data
2.6 Missing values: find, drop or fill
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Real data has holes: a customer skipped a field, a sensor was off. pandas shows a missing number as NaN. You must decide what to do with it before you calculate.
- Find:
df["amount"].isna().sum()counts the missing values - Drop:
df.dropna()removes the rows that have any missing value - Fill:
df["amount"].fillna(0)puts a value in the holes
Which one is right depends on the meaning. A missing amount is not always zero. Ask before you fill.
One NaN turns a whole-number column into decimals: 250 is shown as 250.0. That is normal, not an error.
Find and drop
Ravi has no amount.
Python
import pandas as pddf = pd.DataFrame({ "name": ["Asha", "Ravi", "Meera"], "amount": [250, None, 150],})print(df["amount"].isna().sum())print(df.dropna())
Output
1
name amount
0 Asha 250.0
2 Meera 150.0
Quick check
What does df.dropna() remove?
Fill the hole
Here a missing amount is treated as 0.
Python
import pandas as pddf = pd.DataFrame({ "name": ["Asha", "Ravi", "Meera"], "amount": [250, None, 150],})df["amount"] = df["amount"].fillna(0)print(df)
Output
name amount 0 Asha 250.0 1 Ravi 0.0 2 Meera 150.0
Quick check
After fillna(0), how many missing values are left in that column?
Practice in pandas ✓ Solved
Fill the missing amount with 100 and print df.
Expected output
name amount 0 Asha 250.0 1 Ravi 100.0 2 Meera 150.0
Reference solution
import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Ravi", "Meera"],
"amount": [250, None, 150],
})
df["amount"] = df["amount"].fillna(100)
print(df)
Question 1 · Easy
How does pandas show a missing number?
Question 2 · Medium
Which line counts the missing values in amount?
Question 3 · Hard
A survey has missing ages. Why is fillna(0) a poor choice?
Key takeaways
Find missing values with isna().sum(), remove them with dropna() or replace them with fillna(). Choose by what the missing value means.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in