What you will be able to do
- Choose between distinct() and dropDuplicates(subset) and predict which rows each keeps
- Keep one deterministic row per key with row_number() over a window instead of relying on dropDuplicates
- Drop incomplete rows with dropna using how, thresh and subset
- Repair values with fillna and na.replace and predict which columns they touch
- Count nulls in a column and split a DataFrame into valid and quarantined rows
Key concept
Duplicate comparison set — Spark treats two rows as duplicates when they match on the columns it compares. For distinct() and dropDuplicates() with no arguments, that means every column. When you pass a subset to dropDuplicates, only those columns are compared, and the other columns of the row that survives come along with it.
1.distinct() and dropDuplicates(): which columns define a duplicate
Duplicates get into a pipeline from replayed files, retried loads and sources that send the same record twice. A count, join or aggregate run on top of them comes out wrong, and no error tells you so. Spark gives you two DataFrame methods for removing them. Both return a new DataFrame and leave the input unchanged. What separates them is the set of columns Spark compares.
distinct() compares whole rows. It returns the distinct rows of the DataFrame, so two rows count as duplicates only when every column matches. With [(14, "Tom"), (23, "Alice"), (23, "Alice")] it returns two rows, and distinct().count() returns 2. It takes no arguments, so you can't narrow the comparison.
dropDuplicates(subset) lets you choose the columns. Its only parameter is subset, a list of column names, and it defaults to all columns. With no argument it does exactly what distinct() does, so df.dropDuplicates() is the drop-in replacement when you need the same result. Once you pass a subset, two rows count as duplicates when they agree on those columns, even if they differ everywhere else. On a static batch DataFrame it simply drops the duplicate rows. Its streaming behaviour belongs to streaming deduplication.
df.dropDuplicates().show()
# +-----+---+------+
# | name|age|height|
# +-----+---+------+
# |Alice| 5| 80|
# |Alice| 10| 80|
# +-----+---+------+
df.dropDuplicates(['name', 'height']).show()
# +-----+---+------+
# | name|age|height|
# +-----+---+------+
# |Alice| 5| 80|
# +-----+---+------+In the second call, the age-10 row disappears even though it was never an exact copy. It shared name and height with a row Spark kept. A subset on order_id alone works the same way: it collapses every row with the same order ID, whatever the amounts. Two other calls look like deduplication but aren't. select("order_id").distinct() returns only the order_id column, so the other columns are gone. na.drop() removes rows that contain nulls and leaves exact duplicates in place.
| Call | Rows treated as duplicates | Columns in the result |
|---|---|---|
| df.distinct() | Rows identical in every column | All columns |
| df.dropDuplicates() | Rows identical in every column (default subset is all columns) | All columns |
| df.dropDuplicates(['name', 'height']) | Rows equal on name and height only | All columns |
| df.select("name").distinct() | Rows with equal name | name only |
| df.na.drop() | None: it drops rows containing null or NaN | All columns |
Checkpoint 1 of 8· Fill the gap
A batch DataFrame holds three Alice rows: (age 5, height 80), (age 5, height 80) and (age 10, height 80). This call keeps only one row, even though the age-10 row is not an exact copy. Which method fills the blank?
df. ? (['name', 'height']).show()
# +-----+---+------+
# | name|age|height|
# +-----+---+------+
# |Alice| 5| 80|
# +-----+---+------+Only dropDuplicates takes a subset, so it compares just name and height. That collapses the age-10 row into the row it keeps. distinct() takes no arguments and compares whole rows, so it would keep two rows. dropna removes rows with nulls, so it would keep all three.
Source: docs.databricks.comCheckpoint 2 of 8· Exam question
You have a DataFrame orders_df with columns order_id, customer_id, amount. A teammate wants an exact drop of duplicate rows considering every column and writes orders_df.distinct(). You need to rewrite this using dropDuplicates() so the result is functionally identical. Which call is equivalent?
Correct answer: A — orders_df.dropDuplicates()
- A. Calling dropDuplicates() with no subset compares every column, exactly matching the full-row comparison that distinct() performs.
- B. Restricting the subset to order_id only removes rows that share an order_id, which is narrower than comparing all columns and can drop rows distinct() would keep.
- C. Narrowing the comparison to customer_id alone collapses multiple genuinely different orders from the same customer, producing far fewer rows than a full-row distinct().
- D. na.drop() removes rows containing null values; it performs no deduplication of identical rows at all.
- E. Projecting down to a single column before calling distinct() discards the other columns, so the result cannot match the schema or row set of a full-row distinct().
2.Keeping a specific row per key with row_number()
dropDuplicates(subset) keeps one row per key, but you can't tell it which one. Its signature has a subset parameter and nothing else: no ordering and no "keep first" option. That's fine when the duplicates are exact copies. It isn't fine for a requirement like "keep the earliest reading per device", because the rows in each group differ and the choice of survivor matters.
Sorting first doesn't fix this. To deduplicate, Spark has to bring the rows for each key together, and the order of rows after a shuffle may not be deterministic. That is why Spark's first() aggregate is documented as non-deterministic. An orderBy placed before dropDuplicates is not part of what dropDuplicates promises, so the row you get may change between runs on unchanged data.
For a deterministic result, rank the rows yourself. row_number() is a window function that numbers rows from 1 within each window partition, following the window's ordering. Partition by the key, order by the column that decides the winner, keep rn == 1, then drop the helper column:
w = Window.partitionBy("device_id").orderBy("event_time"), then .withColumn("rn", F.row_number().over(w)).filter(F.col("rn") == 1).drop("rn").
The surviving row keeps all of its columns, payload included.
df = spark.createDataFrame(
[(1, "a"), (1, "a"), (2, "a"), (1, "b"), (2, "b"), (3, "b")], ["id", "category"])
# Show row number ordered by id in each category partition.
window = Window.partitionBy("category").orderBy("id")
df.withColumn("row_number", sf.row_number().over(window)).show()
# +---+--------+----------+
# | id|category|row_number|
# +---+--------+----------+
# | 1| a| 1|
# | 1| a| 2|
# | 2| a| 3|
# | 1| b| 1|
# | 2| b| 2|
# | 3| b| 3|
# +---+--------+----------+Pay attention to ties. row_number() always gives each row a different number, but if two rows tie on the ordering column, which one gets 1 is not deterministic. In category a above, two rows have id 1. They happen to be identical, so it doesn't matter here. With real events it would. If two readings can share an event_time, add a second ordering column so every row in a partition has its own position.
The other approaches each fail in a specific way. dropDuplicates(["device_id", "event_time"]) keeps one row per distinct timestamp, so a device with three readings keeps all three. sort(...).distinct() compares whole rows and removes nothing unless the rows are full copies. groupBy("device_id").agg(F.min("event_time")) finds the right timestamp but returns only the grouping and aggregate columns, so payload is lost.
Checkpoint 3 of 8· Check yourself
You need the earliest reading for each device from events_df (columns device_id, event_time, payload), with payload kept. The pipeline must keep the same row on every run. No two readings of a device share an event_time. Which approach meets the requirement?
The only parameter dropDuplicates takes is subset, so it can't be told which row to keep. Row order after a shuffle may not be deterministic, so sorting first doesn't fix the survivor. Ranking with row_number() and keeping rn == 1 gives the same row every run, with all of its columns. Adding event_time to the subset keeps one row per timestamp, not one per device. groupBy with min loses payload.
“dropDuplicates(subset: Optional[List[str]] = None)”Source: docs.databricks.com
Checkpoint 4 of 8· Exam question
An events_df DataFrame has columns device_id, event_time, payload. Duplicate device readings should be deduplicated so that the **earliest** event_time per device_id is retained, and the result must be deterministic across repeated runs on unchanged data. Which code correctly implements this?
Correct answer: A — from pyspark.sql import Window
from pyspark.sql import functions as F
w = Window.partitionBy("device_id").orderBy("event_time")
result_df = (events_df
.withColumn("rn", F.row_number().over(w))
.filter(F.col("rn") == 1)
.drop("rn"))
- A. A window partitioned by device_id and ordered by event_time with row_number() deterministically ranks readings per device, so filtering rn == 1 always keeps the same earliest row regardless of partitioning or re-execution.
- B. Even after orderBy, dropDuplicates does not guarantee which row within a duplicate group is retained, because Spark does not carry the sort order through the deduplication shuffle, so the kept row can vary between runs.
- C. Deduplicating on both device_id and event_time only removes rows that are exact duplicates on that pair; it does not collapse multiple distinct event_time values down to the earliest one per device.
- D. Aggregating with min(event_time) returns only device_id and the minimum timestamp, dropping the payload column and any other fields from the original row.
- E. distinct() compares the full row across all columns, so it will not deduplicate at the device_id grain at all if payload or event_time differ between duplicate readings.
3.Dropping incomplete rows with dropna: how, thresh and subset
Missing values are the other half of cleaning a dataset. df.dropna() and df.na.drop() are aliases of each other, and both return a new DataFrame without rows that contain null or NaN values. Spark treats NaN as missing here too, which surprises people who think of NaN as a number.
| Parameter | Default | Effect |
|---|---|---|
| how | 'any' | 'any' drops a row containing any null; 'all' drops a row only when every value is null |
| thresh | None | Drops rows with fewer than thresh non-null values; when set, it overrides how |
| subset | None (all columns) | Restricts the null check to the listed columns |
df.na.drop(how='all').show()
# +----+------+-----+
# | age|height| name|
# +----+------+-----+
# | 10| 80.0|Alice|
# | 5| NaN| Bob|
# |NULL| NULL| Tom|
# +----+------+-----+
df.na.drop(thresh=2).show()
# +---+------+-----+
# |age|height| name|
# +---+------+-----+
# | 10| 80.0|Alice|
# | 5| NaN| Bob|
# +---+------+-----+thresh is a minimum count of non-missing values, and it replaces how rather than adding to it. Bob passes thresh=2 because age and name are present, and his NaN height doesn't count toward the two. Tom has only a name, so he is dropped. With the default how='any', only Alice would survive. Use subset when only some columns are required. For example, subset=["email"] drops rows with no email and ignores nulls everywhere else.
Checkpoint 5 of 8· Check yourself
Take the same four rows: Alice complete, Bob with a NaN height, Tom with only a name, and one row of None/NaN/None. Which rows does df.na.drop(how='any', thresh=2) return?
When thresh is set, it replaces how instead of adding a second condition. A row stays only if it has at least thresh non-null values. Alice has three, and Bob has two (age and name; his NaN height doesn't count), so both stay. Tom has one and the last row has none, so both are dropped.
“If specified, drop rows that have less than thresh non-null values. This overwrites the how parameter.”Source: docs.databricks.com
Sources6
4.Repairing values with fillna and na.replace
Dropping a row discards the good values along with the bad one. Often the better fix is to fill the gap. fillna(value, subset), also available as na.fill, replaces nulls with a value. The value must be an int, float, string or bool, or a dict that maps column names to values. Two rules decide which columns change.
First, a scalar only fills columns whose type matches it. na.fill(50) fills the numeric age and height columns, so a null height becomes 50.0, and it leaves the null name and bool values alone. na.fill(False) fills only the boolean column. A column you list in subset that has the wrong type is skipped without an error. Second, a dict takes precedence over subset: with na.fill({'age': 50, 'name': 'unknown'}), Spark ignores subset entirely and fills only the columns named in the dict.
df.na.fill(50).show()
# +---+------+-----+----+
# |age|height| name|bool|
# +---+------+-----+----+
# | 10| 80.5|Alice|NULL|
# | 5| 50.0| Bob|NULL|
# | 50| 50.0| Tom|NULL|
# | 50| 50.0| NULL|true|
# +---+------+-----+----+na.replace(to_replace, value, subset) fixes values that are present but wrong, such as a sentinel or an inconsistent code. DataFrame.replace is an alias for it. to_replace and value must have the same type and can only be numerics, booleans or strings, although value can also be None. Spark casts the new value to the existing column's type. Passing two equal-length lists maps the values pairwise: df.na.replace(['Alice', 'Bob'], ['A', 'B'], 'name') rewrites just those names in name. A scalar value with a list to_replace uses that one value for every item, and a dict to_replace makes value unnecessary. Without a subset, df.na.replace(10, 20) changes 10 to 20 in every numeric column, so an age of 10 and a height of 10 both become 20. df.na.replace('Alice', None) works the other way and turns a known bad value into a null that fillna or dropna can then handle.
Nothing. 0 is an int, so only age is filled. name is in the subset but has a different type, and Spark ignores it without raising an error.
Checkpoint 6 of 8· Fill the gap
In the output below, only the bool column was filled. The null ages, heights and the null name stayed null. Which value was passed to fill?
df.na.fill( ? ).show()
# +----+------+-----+-----+
# | age|height| name| bool|
# +----+------+-----+-----+
# | 10| 80.5|Alice|false|
# | 5| NULL| Bob|false|
# |NULL| NULL| Tom|false|
# |NULL| NULL| NULL| true|
# +----+------+-----+-----+A scalar fill only changes columns whose type matches the value, so the boolean False fills only the bool column. 50 would have filled the numeric age and height columns. A string such as 'unknown' or 'false' would have filled the null name and left bool alone.
Source: docs.databricks.com5.Validation rules: counting nulls and quarantining failing rows
Validation means measuring how much data breaks a rule and then deciding where those rows go. A null count is the most common measurement, and two similar-looking aggregate calls give different numbers.
from pyspark.sql import functions as sf
df = spark.createDataFrame([(None,), ("a",), ("b",), ("c",)], schema=["alphabets"])
df.select(sf.count(sf.expr("*"))).show()
+--------+
|count(1)|
+--------+
| 4|
+--------+
Example 2: Count non-null values in a specific column
from pyspark.sql import functions as sf
df.select(sf.count(df.alphabets)).show()
+----------------+
|count(alphabets)|
+----------------+
| 3|
+----------------+Neither call counts nulls directly. count("email") returns the number of emails that are present, and count("*") returns the total row count. Two patterns do give the null count. One aggregates with F.count(F.when(F.col("email").isNull(), 1)). Because the when has no otherwise(), it returns null for every row that has an email, so count sees a value only on the null rows. The other filters and counts: customers_df.filter(F.col("email").isNull()).count(). Note that na.drop(subset=["email"]).count() counts the opposite set, the rows that do have an email.
The same condition also routes rows. Recall that filter/where keeps only the rows where a condition is true (Filtering rows with filter/where). A validation rule is two complementary filters. isNull() selects the rows that fail the rule, and you write them to a quarantine output for someone to inspect. isNotNull() selects the rows that pass, and those continue down the pipeline. Keeping the failing rows instead of silently dropping them lets you count rejects per run and replay them once the source is fixed.
df = spark.createDataFrame([Row(name='Tom', height=80), Row(name='Alice', height=None)])
df.filter(df.height.isNull()).collect()
# [Row(name='Alice', height=None)]Checkpoint 7 of 8· Check yourself
A data-quality job needs to report how many rows of customers_df are missing an email, and it logs customers_df.na.drop(subset=["email"]).count(). What number does it actually log?
na.drop removes rows with null or NaN values, and subset limits the check to email. The count is therefore the rows that have an email, which is the opposite of what the job wants. To count the missing ones, use filter(F.col("email").isNull()).count() or F.count(F.when(F.col("email").isNull(), 1)).
“Returns a new DataFrame omitting rows with null or NaN values.”Source: docs.databricks.com
Checkpoint 8 of 8· Exam question
You need to validate a customers_df DataFrame by reporting how many rows contain a null value in the email column. Which two approaches correctly compute that null count? (Choose 2 answers)(Select 2)
Correct answers: A, B — customers_df.select(F.count(F.when(F.col("email").isNull(), 1))).collect(); customers_df.filter(F.col("email").isNull()).count()
- A. F.when returns 1 only for rows where email is null and otherwise yields null, and count() ignores those null results, so the aggregation totals exactly the null rows.
- B. Filtering down to rows where email is null before calling count() directly returns the number of null-email rows, which is functionally equivalent to the conditional aggregation.
- C. count("email") counts only the non-null values in that column, which is the opposite of what a null-count validation needs.
- D. count("*") returns the total row count of the DataFrame regardless of whether email is null, so it does not isolate the null rows.
- E. na.drop(subset=["email"]) removes the null rows and counts what remains, returning the non-null count rather than the null count.
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Returns a new DataFrame containing the distinct rows in this DataFrame.”
↩︎ distinct() and dropDuplicates(): which columns define a duplicate - 2.
“List of columns to use for duplicate comparison (default All columns).”
↩︎ distinct() and dropDuplicates(): which columns define a duplicate“For a static batch DataFrame, it just drops duplicate rows.”
↩︎ distinct() and dropDuplicates(): which columns define a duplicate“List of columns to use for duplicate comparison (default All columns).”
↩︎ Key concept“dropDuplicates(subset: Optional[List[str]] = None)”
↩︎ Checkpoint - 3.
“Window function: returns a sequential number starting at 1 within a window partition.”
↩︎ Keeping a specific row per key with row_number() - 4.
“If the order is not unique, the result is non-deterministic.”
↩︎ Keeping a specific row per key with row_number() - 5.
“The function is non-deterministic because its results depends on the order of the rows which may be non-deterministic after a shuffle.”
↩︎ Keeping a specific row per key with row_number()“The function is non-deterministic because its results depends on the order of the rows which may be non-deterministic after a shuffle.”
↩︎ Exam trap 1 - 6.
“Returns a new DataFrame omitting rows with null or NaN values.”
↩︎ Dropping incomplete rows with dropna: how, thresh and subset“If specified, drop rows that have less than thresh non-null values. This overwrites the how parameter.”
↩︎ Dropping incomplete rows with dropna: how, thresh and subset“If 'all', drop a row only if all its values are null.”
↩︎ Dropping incomplete rows with dropna: how, thresh and subset“If specified, drop rows that have less than thresh non-null values. This overwrites the how parameter.”
↩︎ Exam trap 2“Returns a new DataFrame omitting rows with null or NaN values.”
↩︎ Checkpoint - 7.
“If the value is a dict, then subset is ignored and value must be a mapping from column name (string) to replacement value.”
↩︎ Repairing values with fillna and na.replace“Columns specified in subset that do not have matching data types are ignored.”
↩︎ Repairing values with fillna and na.replace“If the value is a dict, then subset is ignored and value must be a mapping from column name (string) to replacement value.”
↩︎ Exam trap 4 - 8.
“Values to_replace and value must have the same type and can only be numerics, booleans, or strings.”
↩︎ Repairing values with fillna and na.replace“When replacing, the new value will be cast to the type of the existing column.”
↩︎ Repairing values with fillna and na.replace - 9.
“Example 2: Count non-null values in a specific column”
↩︎ Validation rules: counting nulls and quarantining failing rows“Example 2: Count non-null values in a specific column”
↩︎ Exam trap 3 - 10.
“If otherwise() is not invoked, None is returned for unmatched conditions.”
↩︎ Validation rules: counting nulls and quarantining failing rows - 11.
“Check if the column value is null.”
↩︎ Validation rules: counting nulls and quarantining failing rows