Transformations, actions, and shuffles
Spark / PySpark · 12 questions
Short notes
Key idea
Transformations (filter, select, groupBy, join) describe new DataFrames lazily. Actions (count, show, collect, write) run them. A shuffle moves data between executors so rows with the same key meet; it's the most expensive part of most jobs.
Syntax
- Narrow transformations: each output partition needs one input partition (
filter,select,withColumn). No shuffle. - Wide transformations: need data from many partitions (
groupBy,join,distinct,orderBy,repartition). Shuffle, and a new stage. df.explain()prints the plan;Exchangemeans a shuffle.
Example
df.filter(...).withColumn(...).groupBy("city").sum("amount").show(): the filter and new column run together in stage 1; the groupBy shuffles rows by city into stage 2; show is the action that triggers it all.
Traps
- Calling several actions on the same DataFrame recomputes it each time; cache it if reused.
- Unneeded
orderByordistinctadd shuffles. - Filter and select early so less data is shuffled.
count()for "debugging" inside a pipeline triggers extra full jobs.
Want the full lesson with step-by-step examples, a project and a certificate? Spark / PySpark course, ₹120 →
- Question 1easy
Which transformation causes a shuffle?
- Question 2easy
Which of these is an action?
- Question 3medium
Ignoring adaptive query execution, how many stages does this job have?
(orders .filter(F.col("amount") > 0) .withColumn("year", F.year("order_date")) .groupBy("customer_id", "year") .agg(F.sum("amount").alias("spend")) .write.parquet("gs://out/spend/")) - Question 4medium
In the output of
df.explain(), which operator means a shuffle? - Question 5medium
Why put filters before a join or groupBy where possible?
Transformations, actions, and shuffles
Transformations, actions, and shuffles
Transformations, actions, and shuffles
Transformations, actions, and shuffles
Transformations, actions, and shuffles
7 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.