CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 13/32

    Deduplicating and validating Spark DataFrames

    Perform data deduplication and validation operations on DataFrames.

    18 min read
    3% of exam
    11 sources
    Published 21 Oct 2026
    Docs as of 30 Sep 2026

    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.

    The same three Alice rows (age 5, age 5, age 10; height 80 each) deduplicated on all columns, then on name and height onlypython
    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.

    Calls that look like deduplication, and what each actually compares
    CallRows treated as duplicatesColumns in the result
    df.distinct()Rows identical in every columnAll 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 onlyAll columns
    df.select("name").distinct()Rows with equal namename only
    df.na.drop()None: it drops rows containing null or NaNAll 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|
    # +-----+---+------+

    Checkpoint 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?

    Sources12

    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.

    row_number() numbers rows within each category partition in id order; filtering on 1 keeps one row per categorypython
    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?

    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?

    Sources345

    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.

    dropna parameters and their effect
    ParameterDefaultEffect
    how'any''any' drops a row containing any null; 'all' drops a row only when every value is null
    threshNoneDrops rows with fewer than thresh non-null values; when set, it overrides how
    subsetNone (all columns)Restricts the null check to the listed columns
    Four rows (Alice complete, Bob with NaN height, Tom with only a name, one row of None/NaN/None) under how='all' and thresh=2python
    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?

    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.

    A scalar fill touches only columns of a matching type: the numeric columns change, name and bool keep their nullspython
    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.

    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|
    # +----+------+-----+-----+

    Sources78

    5.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.

    count("*") counts every row; count(column) counts only the non-null values in that columnpython
    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.

    isNull() as a rule: the row missing a height is the one routed to quarantinepython
    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?

    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)

    0 of 2 selected

    Sources91011

    Sources

    (11)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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
    2. 3.
      “Window function: returns a sequential number starting at 1 within a window partition.”
      ↩︎ Keeping a specific row per key with row_number()
    3. 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
    4. 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
    5. 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
    6. 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
    7. 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
    8. 10.
      “If otherwise() is not invoked, None is returned for unmatched conditions.”
      ↩︎ Validation rules: counting nulls and quarantining failing rows

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.