psypark Cheat Sheet

Published 2026-07-09 in Data Engineering

Most people know what Pivot does. But when asked to write it in PySpark without Googling? Blank. Here is the full breakdown ↓ → What is Pivot? Pivot transforms row values into column headers. Converts long format data into wide format. → What is Unpivot? Unpivot does the opposite. Converts column headers back into row values. Wide format → long format. → When to Use Each Use Pivot when: • You want to compare values ↳ across categories side by side • Creating summary reports ↳ with months or categories as columns • Feeding data into dashboards ↳ that expect wide format Use Unpivot when: • Source data has dynamic columns ↳ that need to become rows • Normalizing data before loading ↳ into a data warehouse • Feeding into ML pipelines ↳ that expect long format → Pivot in PySpark from pyspark.sql import functions as F df.groupBy("product") \ .pivot("month") \ .agg(F.sum("sales")) Input: ↳ product | month | sales ↳ A | Jan | 100 ↳ A | Feb | 200 ↳ B | Jan | 150 Output: ↳ product | Jan | Feb ↳ A | 100 | 200 ↳ B | 150 | null → Pivot with Specific Values (Faster) df.groupBy("product") \ .pivot("month", ["Jan", "Feb", "Mar"]) \ .agg(F.sum("sales")) ↳ Always specify pivot values explicitly ↳ Spark scans data twice without them ↳ Providing values = one pass = faster → Unpivot in PySpark (using stack) from pyspark.sql.functions import expr df.select ( "product", expr(""" stack(2, 'Jan', Jan, 'Feb', Feb ) as (month, sales) """) ) ↳ stack(n, col1_name, col1, col2_name, col2) ↳ n = number of columns to unpivot → Pivot vs Unpivot ✓ Pivot → rows to columns ✕ Unpivot → columns to rows ✓ Pivot → wide format output ✕ Unpivot → long format output ✓ Pivot → uses groupBy + agg ✕ Unpivot → uses stack() expression → Common Interview Gotchas • Pivot without specifying values is slow ↳ always pass the list explicitly • Null values appear when ↳ a combination does not exist ↳ use fillna() after pivot • Unpivot column names must be strings ↳ cast numeric column names first → Interview Tip If they ask "how do you reshape data in Spark from long to wide format?" Say: I use pivot() with groupBy and always specify pivot values explicitly to avoid a double scan. For wide to long I use the stack() function inside a select expression. That complete answer shows you have used this in real pipelines.

More Data Engineering articles · All collections · Practice challenges

Practise what you just read: data engineer interview questions · data engineering projects · Databricks certification practice exams.