Let’s Get Certified
Module 06 / 13 · DataFrame and Dataset APIs

Clean and aggregate DataFrames

Preserve row grain through projections, array expansion, deduplication and grouped metrics.

Clean and aggregate DataFrames

Work through the decision

One ticket sale includes three tags in a delimited string. An analyst splits and explodes the tags, then sums the original fare and reports triple the revenue. Which result grain was intended?

Check your reasoning

Count tickets or revenue at ticket grain before expanding tags. Use split and explode when the desired output is one row per tag. Decide how null and empty arrays should behave. Deduplicate using the business key, and choose a deterministic winner when repeated IDs carry different versions. A simple dropDuplicates on the key cannot promise which differing payload survives.

Watch the source lesson at 1:03:58

Compare the choices

Array expansion
Use split to construct an array from text and explode to emit an element per row. Retain the original key when the result grain changes.
Business-key deduplication
Choose keys that identify the business event. If distinct payloads share the same key, apply a defined version order or data quality rule.
Grouped aggregation
Choose group keys and metrics at the intended grain. count(column) skips nulls, and count of all rows includes them.
Approximate distinct count
Use an approximate cardinality measure only where its error tolerance is acceptable. Compare with exact counts on representative data.
Time normalization
Interpret units, timestamp type and time zone before extracting dates or grouping into reporting periods. Test samples close to midnight.

Test the decision

Count rows and count of a specific nullable column answer different questions. Select an exact distinct count when exactness is required or an approximate distinct count when error bounds and cost are acceptable. For event dates, define whether the timestamp is in seconds or milliseconds and specify the session time zone before extracting the business day.

Predict the grain after explode

from pyspark.sql import functions as F
journeys = spark.createDataFrame([(1, "A,B"), (2, "B")], "trip int, stops string")
visits = journeys.select("trip", F.explode(F.split("stops", ",")).alias("station"))
visits.groupBy("station").count().orderBy("station").show()
Check the result

The expansion creates three trip-stop rows. Station B has two visits. Counting rows after the expansion answers a stop-level question. Counting the input rows answers a trip-level question.

Practice the guide skills

  1. Split a delimited stop list, explode it into rows and filter invalid values after predicting the new row count. Watch 1:03:58 · Continue at 1:05:36 · Continue at 1:06:56
  2. Compare exact row duplicates with conflicting records sharing an event ID and choose a deterministic survivor rule. Watch 1:09:25 · Continue at 1:11:00
  3. Compute total fares and an estimated distinct rider count by station, then explain which metric is approximate. Watch 1:11:28 · Continue at 1:13:12
  4. Convert epoch seconds to a timestamp under UTC and derive a service date for a record near midnight. Watch 1:16:48

Official objectives for this lesson

Related lesson · Spark DataFrame API

Knowledge check

Clean and aggregate DataFrames quiz

Answer 3 questions. Check each answer for an explanation.