Skip to content
Bronze 4 min read · Nulls 3 practice problems ↓

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

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

PySparkSpark SQL

Input: leads

lead_idnamecityscorephone
1AnaPune8098765
2Bonullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →nullnull
3nullnullnullnull
4CyDelhinull12345
5Dinull55null
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

PySparkSpark SQL

Input: leads

lead_idnamecityscorephone
1AnaPune8098765
2Bonullnullnull
3nullnullnullnull
4CyDelhinull12345
5Dinull55null
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
CallKeeps a row whenLeads kept
dropna()No column is null1
dropna(how="all")At least one column is not nullall 5 (lead_id is never null)
dropna(subset=["city"])city is not null1, 4
dropna(thresh=3)At least 3 columns are not null1, 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 valuesavg
80, null, null, null, 5567.5

Output

score valuesavg
80, 0, 0, 0, 5527.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 only fills columns whose type matches the value: 0 fills numeric columns, a string fills string columns. Use a dict to set values per column: fillna({"name": "unknown", "qty": 0}).
Scenario"Should missing revenue be filled with 0?"
Only if missing really means zero (no sale). If it means "not reported", filling with 0 makes averages and totals wrong. Keep nulls, report the count, or fill from a better source with coalesce. Say that this is a business question, not a technical one.
Trap"fillna replaces empty strings too."
No. An empty string is a value, not null. Convert first with F.nullif(F.trim("c"), F.lit("")) or a when() if empty means missing.

Check yourself

3 questions

df 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

See all 4 problems →

Keep going

Up next · new module: Combine and summarise · 4 min read
groupBy + agg
Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).

Related lessons

Previous: when / otherwise

Primary sources: DataFrame.fillna · DataFrame.dropna