Lab: Read, Transform and Write with DataFrames
Generate a month of seeded taxi trips as Parquet, read it, catch a join that multiplies rows, build daily metrics per zone with the DataFrame API and again with Spark SQL on temporary views, write the result partitioned by date and prove that a filtered read opens one folder.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the session helper and the data
- Step 2: Read the Parquet files and inspect them
- Step 3: Clean, join and count the rows
- Step 4: Build the daily metrics with the DataFrame API
- Step 5: Write the same job in Spark SQL
- Step 6: Write partitioned Parquet
- Step 7: Read the output back with a filter
- Check your understanding
- Apply it
- Review prompt
Lessons of Batch Processing with Spark
- From Clusters to Stages: How Spark Runs Your Code Concept · 25 min
- Lab: Read, Transform and Write with DataFrames Lab · 30 min
- Joins and Aggregations at Scale, Shuffle by Shuffle Worked example · 25 min
- Lab: Using the Spark UI to Fix a Slow Job Lab · 30 min
- Testing PySpark Transformations Locally Lab · 20 min
- Check: Plans, Shuffles and Tuning Knowledge check · 8 questions
What you will learn
- Write PySpark DataFrame and Spark SQL code that reads Parquet or table-format data, joins and aggregates it, and writes partitioned output.
Prerequisites: Python Foundations
01. Goal and setup
In this lab you build the core of a batch job: read Parquet, clean it, join it with a lookup table, aggregate, and write partitioned output that readers can filter cheaply. You write the aggregation twice, with the DataFrame API and in Spark SQL, and prove that both give the same rows and plan. On the way you meet two classic bugs: a join that silently multiplies rows, and a write that creates far more files than you expect.
The lab was tested with PySpark 4.3.0, Python 3.12 and Eclipse Temurin JRE 21.0.12.1 in local mode. Set up Java and the venv as in the first lesson, then work inside spark-lab/ with the venv active. The data is about 4 MB. For background on folder layouts, see Object Storage, Partitioning and the Small-Files Problem.
spark-lab/
├── session.py step 1: local SparkSession and plan helpers
├── make_data.py step 1: seeded trips and zones as Parquet
├── inspect_data.py step 2: schema, counts and partitions
├── join_check.py step 3: row counts before and after the join
├── pipeline.py step 4: clean, deduplicate and aggregate
├── daily_api.py step 4: the job with the DataFrame API
├── daily_sql.py step 5: the same job in Spark SQL
├── write_output.py step 6: partitioned writes
├── read_back.py step 7: a filtered read that skips folders
├── data/ inputs written by make_data.py
└── out/ outputs written by write_output.py02. Step 1: Create the session helper and the data
Every script in this skill starts Spark through one helper. local_session runs in local mode, binds the driver to 127.0.0.1, prints timestamps in UTC whatever your time zone, and hides the progress bar. plan captures explain() without the expression ids, and operators keeps only the operator names. rest and stage_table read the Spark UI's REST API; lesson 3 uses them.
import contextlib
import io
import json
import re
import urllib.request
from pyspark.sql import SparkSession
def local_session(app_name, cores=4, conf=None):
"""A local Spark session: driver and executor share one JVM on this machine."""
builder = (
SparkSession.builder.master(f"local[{cores}]")
.appName(app_name)
.config("spark.driver.host", "127.0.0.1")
.config("spark.driver.bindAddress", "127.0.0.1")
.config("spark.ui.showConsoleProgress", "false")
.config("spark.sql.session.timeZone", "UTC")
)
for key, value in (conf or {}).items():
builder = builder.config(key, value)
spark = builder.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
return spark
def plan(df, width=84):
"""The physical plan without expression ids (#12L), each line cut to `width`."""
buffer = io.StringIO()
with contextlib.redirect_stdout(buffer):
df.explain()
lines = [line for line in buffer.getvalue().splitlines()[1:] if line.strip()]
return [re.sub(r"#\d+L?", "", line)[:width] for line in lines]
def operators(df):
"""Only the operator names of the physical plan, top to bottom."""
names = [re.sub(r"^[\s:+\-*()\d]*", "", line) for line in plan(df)]
return [re.split(r"[ (\[]", name)[0] for name in names]
def rest(spark, path):
"""GET a Spark UI REST endpoint of this application and decode the JSON."""
sc = spark.sparkContext
url = f"{sc.uiWebUrl}/api/v1/applications/{sc.applicationId}/{path}"
with urllib.request.urlopen(url) as response:
return json.load(response)
def stage_table(spark, group):
"""Row counts per stage for the jobs of one job group, read from the REST API."""
jobs = [job for job in rest(spark, "jobs") if job.get("jobGroup") == group]
print("stage tasks input rows shuffle write shuffle read")
for stage_id in sorted({s for job in jobs for s in job["stageIds"]}):
stage = rest(spark, f"stages/{stage_id}")[0]
if stage["status"] == "SKIPPED":
continue
print(
f"{stage_id:>5} {stage['numTasks']:>5} {stage['inputRecords']:>10}"
f" {stage['shuffleWriteRecords']:>13} {stage['shuffleReadRecords']:>12}"
)make_data.py writes 200,000 trips for March 2026 in 4 Parquet files, and a lookup of 12 zones. rand(seed) repeats its numbers on every run while the partition count stays fixed. The data has three flaws on purpose: about 1% of trips start in zone 13, which has no zone row; a few trips have a distance of 0 or no fare; and zone 7 appears twice, because it was renamed in February.
import datetime as dt
from pyspark.sql import functions as F
from session import local_session
spark = local_session("make-data")
start = int(dt.datetime(2026, 3, 1, tzinfo=dt.timezone.utc).timestamp())
month = 31 * 24 * 3600
# rand(seed) gives the same numbers on every run while the partition count is fixed.
r = F.col("r")
trips = (
spark.range(0, 200_000, numPartitions=4)
.select(
(F.col("id") + 1).alias("trip_id"),
F.timestamp_seconds(F.lit(start) + F.floor(F.rand(1) * month))
.alias("pickup_ts"),
F.when(F.rand(2) < 0.01, 13) # zone 13 has no row in zones
.otherwise(1 + F.floor(F.rand(3) * 12))
.cast("int")
.alias("pickup_zone_id"),
F.round(0.5 + F.rand(4) * 20, 1).alias("distance_km"),
F.rand(5).alias("r"),
)
.withColumn("distance_km", F.when(r < 0.004, 0.0).otherwise(F.col("distance_km")))
.withColumn(
"fare",
F.when(r > 0.997, None)
.otherwise(F.round(3 + F.col("distance_km") * 1.8 + r * 4, 2))
.cast("decimal(8,2)"),
)
.drop("r")
)
trips.write.mode("overwrite").parquet("data/trips")
rows = [
(1, "Airport", "East"), (2, "Old Town", "Central"), (3, "Harbour", "South"),
(4, "University", "North"), (5, "Market", "Central"), (6, "Stadium", "East"),
(7, "Riverside", "South"), (8, "Hillside", "North"), (9, "Station", "Central"),
(10, "Docklands", "South"), (11, "Parkway", "West"), (12, "Lakeside", "West"),
]
zones = [(*row, dt.date(2025, 1, 1)) for row in rows]
zones.append((7, "Riverside Park", "South", dt.date(2026, 2, 15))) # a renamed zone
spark.createDataFrame(
zones, "zone_id int, zone_name string, borough string, updated_on date"
).coalesce(1).write.mode("overwrite").parquet("data/zones")
print("trips:", spark.read.parquet("data/trips").count(), "rows")
print("zones:", spark.read.parquet("data/zones").count(), "rows")
spark.stop()python make_data.pytrips: 200000 rows
zones: 13 rowsSpark first prints warnings to standard error, such as Unable to load native-hadoop library. They are harmless in local mode and left out of the outputs.
03. Step 2: Read the Parquet files and inspect them
Parquet stores the schema in each file, so spark.read.parquet knows the column names and types without a scan. The number of partitions after a read depends on file sizes and on spark.sql.files.maxPartitionBytes (128 MB by default); here there are four small files, so there are four partitions.
from session import local_session
spark = local_session("inspect")
trips = spark.read.parquet("data/trips")
zones = spark.read.parquet("data/zones")
trips.printSchema()
print("trip rows:", trips.count(), "| partitions:", trips.rdd.getNumPartitions())
trips.orderBy("trip_id").show(3)
zones.orderBy("zone_id", "updated_on").show(20)
spark.stop()python inspect_data.pyroot
|-- trip_id: long (nullable = true)
|-- pickup_ts: timestamp (nullable = true)
|-- pickup_zone_id: integer (nullable = true)
|-- distance_km: double (nullable = true)
|-- fare: decimal(8,2) (nullable = true)
trip rows: 200000 | partitions: 4
+-------+-------------------+--------------+-----------+-----+
|trip_id| pickup_ts|pickup_zone_id|distance_km| fare|
+-------+-------------------+--------------+-----------+-----+
| 1|2026-03-20 17:27:56| 4| 19.6|38.38|
| 2|2026-03-19 13:56:31| 9| 1.8| 6.62|
| 3|2026-03-05 04:19:22| 12| 3.4|12.20|
+-------+-------------------+--------------+-----------+-----+
only showing top 3 rows
+-------+--------------+-------+----------+
|zone_id| zone_name|borough|updated_on|
+-------+--------------+-------+----------+
| 1| Airport| East|2025-01-01|
| 2| Old Town|Central|2025-01-01|
| 3| Harbour| South|2025-01-01|
| 4| University| North|2025-01-01|
| 5| Market|Central|2025-01-01|
| 6| Stadium| East|2025-01-01|
| 7| Riverside| South|2025-01-01|
| 7|Riverside Park| South|2026-02-15|
| 8| Hillside| North|2025-01-01|
| 9| Station|Central|2025-01-01|
| 10| Docklands| South|2025-01-01|
| 11| Parkway| West|2025-01-01|
| 12| Lakeside| West|2025-01-01|
+-------+--------------+-------+----------+Every column is nullable = true: Parquet files written by Spark mark columns as nullable, so the schema tells you nothing about whether nulls really occur. The zone table shows the problem row: zone 7 has an old and a new name.
04. Step 3: Clean, join and count the rows
Before any aggregation, check that a join keeps the number of rows you expect. A trip has one pickup zone, so a left join from trips to zones should return exactly one row per clean trip: no more, because each trip matches at most one zone, and no fewer, because a left join keeps trips without a match.
from pyspark.sql import functions as F
from session import local_session
spark = local_session("join-check")
trips = spark.read.parquet("data/trips")
zones = spark.read.parquet("data/zones")
clean = trips.filter(F.col("fare").isNotNull() & (F.col("distance_km") > 0))
print("clean trips:", clean.count())
joined = clean.join(zones, clean.pickup_zone_id == zones.zone_id, "left")
print("rows after join:", joined.count())
print("trips without a zone:", joined.filter(F.col("zone_id").isNull()).count())
zones.groupBy("zone_id").count().filter("count > 1").show()
spark.stop()python join_check.pyclean trips: 198646
rows after join: 214887
trips without a zone: 1992
+-------+-----+
|zone_id|count|
+-------+-----+
| 7| 2|
+-------+-----+The join returned 214,887 rows for 198,646 trips. A join emits one row per matching pair, so each zone 7 trip matched both zone 7 rows and came out twice: 16,241 extra rows. This is fan-out, and it inflates every count and sum after the join, without any warning. The 1,992 trips without a zone are the zone 13 trips, kept by the left join with null zone columns. Check counts like this after every join on a key you have not proved unique.
05. Step 4: Build the daily metrics with the DataFrame API
Put the logic in functions that take DataFrames and return a DataFrame, with no reads or writes inside. Lesson 5 tests these same functions. latest_zones keeps one row per zone with a window function: it numbers the rows of each zone, newest first, and keeps number 1. Do not use dropDuplicates(["zone_id"]) here: it keeps an arbitrary row per key, so a rerun could pick the old name. daily_zone_metrics joins, replaces missing zone names with Unknown and aggregates per date and zone.
from pyspark.sql import DataFrame, Window
from pyspark.sql import functions as F
def clean_trips(trips: DataFrame) -> DataFrame:
"""Drop trips without a fare or with no distance, and add the pickup date."""
valid = F.col("fare").isNotNull() & (F.col("distance_km") > 0)
return trips.filter(valid).withColumn("pickup_date", F.to_date("pickup_ts"))
def latest_zones(zones: DataFrame) -> DataFrame:
"""Keep one row per zone_id: the most recently updated one."""
newest_first = Window.partitionBy("zone_id").orderBy(F.col("updated_on").desc())
return (
zones.withColumn("rn", F.row_number().over(newest_first))
.filter("rn = 1")
.drop("rn", "updated_on")
)
def daily_zone_metrics(trips: DataFrame, zones: DataFrame) -> DataFrame:
"""One row per pickup date and zone: trip count, revenue and average distance."""
joined = trips.join(zones, trips.pickup_zone_id == zones.zone_id, "left")
return joined.groupBy(
"pickup_date",
F.coalesce("borough", F.lit("Unknown")).alias("borough"),
F.coalesce("zone_name", F.lit("Unknown")).alias("zone_name"),
).agg(
F.count("*").alias("trips"),
F.sum("fare").alias("revenue"),
F.round(F.avg("distance_km"), 2).alias("avg_km"),
)from session import local_session
from pipeline import clean_trips, daily_zone_metrics, latest_zones
spark = local_session("daily-api")
trips = clean_trips(spark.read.parquet("data/trips"))
zones = latest_zones(spark.read.parquet("data/zones"))
joined = trips.join(zones, trips.pickup_zone_id == zones.zone_id, "left")
print("clean trips:", trips.count(), "| rows after join:", joined.count())
daily = daily_zone_metrics(trips, zones)
print("daily rows:", daily.count())
daily.orderBy("pickup_date", "zone_name").show(5)
spark.stop()python daily_api.pyclean trips: 198646 | rows after join: 198646
daily rows: 403
+-----------+-------+---------+-----+--------+------+
|pickup_date|borough|zone_name|trips| revenue|avg_km|
+-----------+-------+---------+-----+--------+------+
| 2026-03-01| East| Airport| 502|11654.07| 10.11|
| 2026-03-01| South|Docklands| 530|12991.21| 10.83|
| 2026-03-01| South| Harbour| 507|12581.77| 11.02|
| 2026-03-01| North| Hillside| 546|12971.37| 10.45|
| 2026-03-01| West| Lakeside| 541|12718.87| 10.34|
+-----------+-------+---------+-----+--------+------+
only showing top 5 rowsThe join now keeps 198,646 rows, one per trip. The result has 403 rows: 31 days times 13 zones, the 12 real zones plus Unknown. revenue is exact, because the fare column is a decimal; with a double you would see rounding noise in the last digits.
06. Step 5: Write the same job in Spark SQL
createOrReplaceTempView gives a DataFrame a name that SQL can use in this session; it copies no data. The query repeats steps 3 and 4 with two CTEs and QUALIFY, which filters on a window function without a subquery. The script then compares the SQL and DataFrame results in both directions with exceptAll, which keeps duplicates, and compares the schemas and the physical operators.
from session import local_session, operators, plan
from pipeline import clean_trips, daily_zone_metrics, latest_zones
spark = local_session("daily-sql")
spark.read.parquet("data/trips").createOrReplaceTempView("trips")
spark.read.parquet("data/zones").createOrReplaceTempView("zones")
daily_sql = spark.sql("""
WITH clean AS (
SELECT *, to_date(pickup_ts) AS pickup_date
FROM trips
WHERE fare IS NOT NULL AND distance_km > 0
),
zones_latest AS (
SELECT zone_id, zone_name, borough
FROM zones
QUALIFY row_number() OVER (PARTITION BY zone_id ORDER BY updated_on DESC) = 1
)
SELECT pickup_date,
coalesce(z.borough, 'Unknown') AS borough,
coalesce(z.zone_name, 'Unknown') AS zone_name,
count(*) AS trips,
sum(fare) AS revenue,
round(avg(distance_km), 2) AS avg_km
FROM clean AS t
LEFT JOIN zones_latest AS z ON t.pickup_zone_id = z.zone_id
GROUP BY 1, 2, 3
""")
daily_api = daily_zone_metrics(
clean_trips(spark.table("trips")), latest_zones(spark.table("zones"))
)
print("SQL rows:", daily_sql.count(), "| API rows:", daily_api.count())
print("only in SQL:", daily_sql.exceptAll(daily_api).count())
print("only in API:", daily_api.exceptAll(daily_sql).count())
print("same schema:", daily_sql.schema == daily_api.schema)
print("same operators:", operators(daily_sql) == operators(daily_api))
print("\n".join(plan(daily_sql)[:9]))
spark.stop()python daily_sql.pySQL rows: 403 | API rows: 403
only in SQL: 0
only in API: 0
same schema: True
same operators: True
AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[pickup_date, _groupingexpression, _groupingexpression], funct
+- Exchange hashpartitioning(pickup_date, _groupingexpression, _groupingexpressio
+- HashAggregate(keys=[pickup_date, _groupingexpression, _groupingexpression],
+- Project [distance_km, fare, pickup_date, coalesce(borough, Unknown) AS _
+- BroadcastHashJoin [pickup_zone_id], [zone_id], LeftOuter, BuildRight,
:- Project [pickup_zone_id, distance_km, fare, cast(pickup_ts as date
: +- Filter ((isnotnull(distance_km) AND isnotnull(fare)) AND (dista
: +- FileScan parquet [pickup_ts,pickup_zone_id,distance_km,fare]Same rows, same schema, same operators. Spark SQL and the DataFrame API are two ways to build one logical plan, and Catalyst optimises it the same way, so choose whichever your team reads more easily; spark.sql returns a DataFrame, and any DataFrame can become a view. The plan shows a BroadcastHashJoin: the zone table is tiny, so Spark copied it to every task instead of shuffling the trips. Lesson 3 explains that choice.
07. Step 6: Write partitioned Parquet
write.partitionBy("pickup_date") creates one folder per value, named pickup_date=2026-03-01 and so on, and leaves the column out of the files, because the folder name holds it. This Hive-style layout lets readers skip whole folders. The script writes the daily metrics, then the clean trips twice, to show how the number of files depends on what happens before the write.
from pathlib import Path
from session import local_session
from pipeline import clean_trips, daily_zone_metrics, latest_zones
def describe(path):
folders = sorted(p.name for p in Path(path).iterdir() if p.is_dir())
files = list(Path(path).glob("*/*.parquet"))
print(f"{path}: {len(folders)} folders, {len(files)} files, first {folders[0]}")
spark = local_session("write-output")
trips = clean_trips(spark.read.parquet("data/trips"))
zones = latest_zones(spark.read.parquet("data/zones"))
daily = daily_zone_metrics(trips, zones)
daily.write.mode("overwrite").partitionBy("pickup_date").parquet("out/daily_zone")
describe("out/daily_zone")
# The cleaned trips, partitioned the same way: 4 read tasks each write every date.
trips.write.mode("overwrite").partitionBy("pickup_date").parquet("out/trips_v1")
describe("out/trips_v1")
# Repartition by the folder column first: each date then lives in one task.
(
trips.repartition("pickup_date")
.write.mode("overwrite")
.partitionBy("pickup_date")
.parquet("out/trips_v2")
)
describe("out/trips_v2")
spark.stop()python write_output.pyout/daily_zone: 31 folders, 31 files, first pickup_date=2026-03-01
out/trips_v1: 31 folders, 124 files, first pickup_date=2026-03-01
out/trips_v2: 31 folders, 31 files, first pickup_date=2026-03-01Each write task writes one file for every folder value it holds. The trips came from 4 read partitions that each held all 31 days, so trips_v1 got 4 × 31 = 124 files; hundreds of tasks and a year of dates would give tens of thousands of small files. repartition("pickup_date") first shuffles all trips of a date into one partition, which gives one file per folder. The daily metrics were already shuffled by date in the aggregation, and AQE merged them into one partition, so they also got one file per folder.
Keep three similar names apart. repartition changes the partitions in memory and costs a shuffle. partitionBy on the writer sets the folder layout on storage. bucketBy hashes rows into a fixed number of files and works only with saveAsTable, which records the buckets in a table catalogue: df.write.bucketBy(4, "zone_name").parquet(path) fails with 'save' does not support bucketBy right now.
08. Step 7: Read the output back with a filter
Reading out/daily_zone, Spark discovers pickup_date from the folder names and adds it as a column. A filter on it becomes a partition filter, applied to folder names before any file is listed. A filter on a normal column becomes a pushed filter: the Parquet reader uses it to skip row groups by their min and max values, but still opens every file. The script prints both, then reads the scan metrics from the REST API.
import re
from pyspark.sql import functions as F
from session import local_session, plan, rest
spark = local_session("read-back")
daily = spark.read.parquet("out/daily_zone")
daily.printSchema()
one_day = daily.filter(F.col("pickup_date") == "2026-03-14").filter("trips > 520")
scan = next(line for line in plan(one_day, width=1000) if "FileScan" in line)
print(re.search(r"PartitionFilters: \[[^\]]*\]", scan).group())
print(re.search(r"PushedFilters: \[[^\]]*\]", scan).group())
one_day.orderBy("zone_name").show()
last_query = rest(spark, "sql?details=true")[-1]
for node in last_query["nodes"]:
if node["nodeName"].startswith("Scan parquet"):
for metric in node["metrics"]:
if metric["name"] in ("number of files read", "number of partitions read"):
print(f'{metric["name"]}: {metric["value"]}')
spark.stop()python read_back.pyroot
|-- borough: string (nullable = true)
|-- zone_name: string (nullable = true)
|-- trips: long (nullable = true)
|-- revenue: decimal(18,2) (nullable = true)
|-- avg_km: double (nullable = true)
|-- pickup_date: date (nullable = true)
PartitionFilters: [isnotnull(pickup_date), (pickup_date = 2026-03-14)]
PushedFilters: [IsNotNull(trips), GreaterThan(trips,520)]
+-------+--------------+-----+--------+------+-----------+
|borough| zone_name|trips| revenue|avg_km|pickup_date|
+-------+--------------+-----+--------+------+-----------+
| South| Docklands| 546|12855.66| 10.31| 2026-03-14|
| North| Hillside| 551|12892.74| 10.24| 2026-03-14|
|Central| Market| 526|12197.12| 10.11| 2026-03-14|
| West| Parkway| 549|13235.81| 10.57| 2026-03-14|
| South|Riverside Park| 527|12503.74| 10.41| 2026-03-14|
| East| Stadium| 547|13043.74| 10.5| 2026-03-14|
+-------+--------------+-----+--------+------+-----------+
number of files read: 1
number of partitions read: 1PartitionFilters holds the date condition, and the scan opened 1 file in 1 of 31 folders; trips > 520 is a pushed filter. pickup_date is now the last column, because partition columns follow the data columns on read. Partition by columns that most queries filter on and that have a modest number of values, such as a date; trip_id would create one folder per row.
09. Check your understanding
10. Apply it
The practice project asks for a year of trips joined with a zone lookup, daily metrics per zone, and partitioned Parquet. Grow this lab towards it:
- Change
make_data.pyto write 12 months, then check the number of files inout/trips_v1andout/trips_v2against the rule from step 6. - Add a
pickup_monthcolumn and write the daily metrics withpartitionBy("pickup_month")instead. Compare the folder count and the number of files read by a one-day query. - Add a row-count check after the join to
daily_api.pythat raises an error when the join returns more rows than it received.
11. Review prompt
Without looking back, explain in your own words:
- how you noticed the fan-out, and why Spark did not warn you about it;
- why
row_number()overupdated_onis safer thandropDuplicatesfor picking the current zone row; - why the SQL version and the DataFrame version run the same plan;
- why
trips_v1got 124 files, and whatrepartitionchanged; - the difference between
PartitionFiltersandPushedFilters.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.