fillna / dropna
Real data has gaps: a missing amount, an empty city. Sometimes a default is right, sometimes the row should go, and sometimes the gap must stay a gap. This lesson shows fillna and dropna, their options, and how to tell which choice is honest for each column.
Step 1 · PySpark functions · Bronze · Clean and type, lesson 5 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: filter / where (skip if you know it)
In plain words first
A survey has unanswered questions. You can write a default into the empty boxes ("0 children" if none were listed), throw away forms with too many empty boxes, or leave the boxes empty because "unknown" is the truth.
fillna is the first, dropna the second, and doing nothing is often the third and best choice. Filling "unknown income" with 0 would make everyone look poorer.
fillna
Input: leads
| lead_id | name | city | score | phone |
|---|---|---|---|---|
| 1 | Ana | Pune | 80 | 98765 |
| 2 | Bo | nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → | null | null |
| 3 | null | null | null | null |
| 4 | Cy | Delhi | null | 12345 |
| 5 | Di | null | 55 | null |
result = leads.fillna({"city": "unknown", "score": 0})
SELECT lead_id, name, coalesce(city, 'unknown') AS city, coalesce(score, 0) AS score, phone FROM leads
Each column gets its own default, and columns not in the dict keep their nulls. SQL has no fillna: coalesce(col, default) per column is the equivalent.
The type rule
fillna(0) fills only numeric columns, and fillna("n/a") fills only string columns. Nothing errors when a column is skipped, so leads.fillna(0) leaves city null and it is easy to think everything was filled. A dict makes the intent explicit and avoids the surprise.
dropna
Input: leads
| lead_id | name | city | score | phone |
|---|---|---|---|---|
| 1 | Ana | Pune | 80 | 98765 |
| 2 | Bo | null | null | null |
| 3 | null | null | null | null |
| 4 | Cy | Delhi | null | 12345 |
| 5 | Di | null | 55 | null |
result = leads.dropna(thresh=3)
SELECT * FROM leads WHERE (CASE WHEN lead_id IS NOT NULL THEN 1 ELSE 0 END + CASE WHEN name IS NOT NULL THEN 1 ELSE 0 END + CASE WHEN city IS NOT NULL THEN 1 ELSE 0 END + CASE WHEN score IS NOT NULL THEN 1 ELSE 0 END + CASE WHEN phone IS NOT NULL THEN 1 ELSE 0 END) >= 3
| Call | Keeps a row when | Leads kept |
|---|---|---|
dropna() | No column is null | 1 |
dropna(how="all") | At least one column is not null | all 5 (lead_id is never null) |
dropna(subset=["city"]) | city is not null | 1, 4 |
dropna(thresh=3) | At least 3 columns are not null | 1, 4, 5 |
thresh overrides how. subset limits which columns are checked, and it combines with both.
When not to fill
A null often carries meaning: "not measured", "not applicable", "not yet known". Filling a missing score with 0 makes avg(score) lower, because avg ignores nulls but not zeros. Fill for display and for columns where a default is truly correct (a missing quantity in a cart is 0); keep nulls in data used for statistics.
Input
| score values | avg |
|---|---|
| 80, null, null, null, 55 | 67.5 |
Output
| score values | avg |
|---|---|
| 80, 0, 0, 0, 55 | 27.0 |
avg(score) before and after fillna(0)
Related tools
coalesce(a, b, c)fills from other columns, not a constant: see the coalesce lesson.df.na.replace(["N/A", ""], None, subset=["city"])turns placeholder strings into real nulls first, so fillna and dropna see them.- For a forward fillforward fill: Copy the last known value down into the empty rows after it, until a new value appears. Learn more → (use the last known value), use
last(col, ignorenulls=True)over a window.
Common mistakes
- Assuming fillna(0) filled every column — It skips non-numeric columns silently. Use a dict.
- Filling before computing averages — avg ignores nulls; zeros pull the average down.
- dropna() with no subset on wide tables — One optional column being null removes the whole row. Pass subset with the columns that must exist.
- Treating "" and "N/A" as missing — They are values, not nulls. Replace them with null first.
Key takeaways
- fillna with a dict fills per column; a single value only fills matching types.
- dropna: subset picks the columns, how="all" or thresh decides how many nulls are too many.
- Filling changes statistics; keep meaningful nulls.
- Turn placeholder strings into nulls before cleaning.
Interview prep
THE QUESTION
"Remove leads that have neither a phone nor an email, and fill a missing city with 'unknown'."
leads.dropna(how="all", subset=["phone", "email"]).fillna({"city": "unknown"}). Explain that how="all" with a subset keeps rows where at least one contact exists, and that a dict in fillna avoids the type-matching surprise. Mention converting empty strings to null first if the source uses them.Avoid: "dropna() then fillna()" with no arguments. Without a subset, dropna removes rows with a null in any column.
Follow-ups · answer out loud, then open
Follow-up"Why did fillna(0) leave nulls in the name column?"
fillna({"name": "unknown", "qty": 0}).Scenario"Should missing revenue be filled with 0?"
Trap"fillna replaces empty strings too."
F.nullif(F.trim("c"), F.lit("")) or a when() if empty means missing.Check yourself
3 questionsdf has a null in a string column city. What does df.fillna(0) do to it?
Show the answer
Leaves it null. A numeric fill value only applies to numeric columns.
Which call keeps rows with at least 3 non-null values?
Show the answer
dropna(thresh=3). thresh is the minimum number of non-null values a row needs.
Scores are 80, null, 60. What is avg(score) after fillna(0)?
Show the answer
46.67. (80 + 0 + 60) / 3. Without filling, avg ignores the null and gives 70.
Practise this
Problems that use fillna / dropna, graded on hidden tests
- Replace Missing ValuesNull Handling Easy
- Data Quality: Null Count per ColumnNull Handling Medium
- Pivot with Several AggregationsPivot, Unpivot & Rollup AdvancedHard
Keep going
Up next · new module: Combine and summarise · 4 min readgroupBy + agg
Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).
Related lessons
coalescePySpark functions · 5 min read
filter / wherePySpark functions · 4 min read
last(ignorenulls)
Previous: when / otherwise
Primary sources: DataFrame.fillna · DataFrame.dropna