Skip to the page
Tecyfy

PySpark cheat sheet

The PySpark you write most, and what each line does to a real table on Spark 4.2.

Run on PySpark 4.2.0

Pick a stop, then a task

Start a Spark session

from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F

spark = SparkSession.builder.appName("orders").getOrCreate()
print(spark.version)

On Databricks the session already exists as spark; skip the builder. Spark docs

What it prints

4.2.0

Every snippet, every common mistake and every pipeline was run on Spark 4.2 against the same 8 orders, so the rows you see are the rows you will get. The cost is read from Spark's own plan: a shuffle is when Spark moves rows between machines, the slow part of a job on big data. Print the page to get every snippet on paper.

Questions

Is this PySpark cheat sheet up to date for Spark 4?
Yes. Every snippet was run on PySpark 4.2.0 and the output shown is what it printed. It uses Spark 4 behaviour, such as ANSI mode being on by default, which changes what a bad cast does.
Does this PySpark code work on Databricks?
Yes. Databricks runs Apache Spark, so the DataFrame code is the same. Skip the session builder, because a Databricks notebook already has spark, and read from tables or volumes instead of local folders.
What is the difference between PySpark and pandas?
pandas works on data in one machine's memory. PySpark splits the data across many machines and runs the work lazily, only when you ask for a result such as show, count or write, so it handles data far larger than one machine's memory.
What is a shuffle in PySpark?
A shuffle is when Spark moves rows between machines so that rows with the same key end up together. dropDuplicates, groupBy, window functions, joins and orderBy cause one; filter, withColumn, fillna and dropna do not. On big data the shuffle is usually the slowest and most costly part of a job, which is why each snippet here shows how many it needs.
How do I clean data in PySpark?
Drop exact duplicates with dropDuplicates(), keep the latest row per key with row_number over a window ordered newest first, then handle missing values with dropna(subset=[...]) or fillna({...}). In the Clean stop of this page you can add those steps to one pipeline and copy it as a script.
Can I print this PySpark cheat sheet as a PDF?
Yes. Print the page from your browser and choose Save as PDF. The search, the menus and the outputs' frames are left out of the print, so the snippets fit on fewer pages.

Sources

Where each fact comes from

  1. 1PySpark API reference (Spark 4.2.0)
  2. 2ANSI compliance in Spark SQL
  3. 3Performance tuning (join strategy hints, autoBroadcastJoinThreshold)
  4. 4RDD programming guide, shuffle operations