Set a DataFrame's partition count with repartition or coalesce
Write set_partitions(df, n) that returns df with exactly n partitions, choosing between repartition and coalesce.
Constraints: when n is below the current count, avoid a full shuffle; when it is above, the count must actually grow; rows must not change. This runs in a classic PySpark session, so df.rdd is available (it is not under Spark Connect).
from pyspark.sql import DataFrame
def set_partitions(df: DataFrame, n: int) -> DataFrame:
# your code hereWrite the implementation.
Read the count via df.rdd.getNumPartitions(). To lower it, coalesce(n) merges partitions without a shuffle but can only reduce (coalesce(50) on 10 stays 10); to raise it, repartition(n) shuffles fully. coalesce(1) squeezes upstream work into one task.
- Expecting
coalesce(50)to raise 10 partitions to 50 - Putting
coalesce(1)before a write and making the whole stage single-threaded - Thinking
repartitionavoids a shuffle because it only renumbers partitions
- When is
repartition(n)the better way to lower the partition count? - What does
repartition('col')give you thatrepartition(n)does not?
Read the current partition count and pick the operation by direction.
from pyspark.sql import DataFrame
def set_partitions(df: DataFrame, n: int) -> DataFrame:
current = df.rdd.getNumPartitions()
if n < current:
return df.coalesce(n) # narrow: merges neighbouring partitions, no shuffle
if n > current:
return df.repartition(n) # full shuffle: the only way the count grows
return dfcoalesce is a narrow transformation: it glues existing partitions together, so it cannot create new ones — coalesce(50) on 10 partitions returns the same 10. repartition(n) spreads the rows over n partitions through a shuffle: costly, but the count can grow and the data gets rebalanced.
The trap: coalesce joins the same stage as the work before it. coalesce(1) before a write turns that stage's read, filters and computation into one task. When the upstream work is heavy and you need few partitions, prefer repartition(n): it adds a shuffle, but the stage before it keeps its full parallelism.