Skip to content

PySpark Cookbook

These recipes show native PySpark patterns for common data tasks. Each example uses synthetic input with an explicit schema and an assertion over a small result. The collect() calls are test actions over bounded local data; keep driver collection out of transformations used on production-sized frames.

The examples target CPython 3.11.18, PySpark 3.5.8, and Eclipse Temurin 17.0.21.1+2, the tuple used for the portal's separately verified getting- started example. This is not a support claim for every PySparky repository. See the style guide for general composition, execution, and correctness guidance.

Choose a preferred, fallback, or default value

Use coalesce when the first non-NULL input has priority. The order of its arguments is the precedence rule. SQL NULL is skipped; an empty string and a floating-point NaN are values, so they are not skipped by this expression.

from pyspark.sql import SparkSession, functions as F, types as T

schema = T.StructType(
    [
        T.StructField("id", T.LongType(), nullable=False),
        T.StructField("preferred", T.StringType(), nullable=True),
        T.StructField("fallback", T.StringType(), nullable=True),
    ]
)
rows = [
    (1, None, "Ava"),
    (2, "", "Bo"),
    (3, None, None),
]

spark = (
    SparkSession.builder.master("local[1]")
    .appName("pysparky-cookbook-coalesce")
    .config("spark.ui.enabled", "false")
    .getOrCreate()
)
try:
    source = spark.createDataFrame(rows, schema)
    result = source.withColumn(
        "display_name",
        F.coalesce(
            F.col("preferred"),
            F.col("fallback"),
            F.lit("Unknown"),
        ),
    )
    actual = [
        (row.id, row.display_name)
        for row in result.orderBy("id").select("id", "display_name").collect()
    ]
    assert actual == [(1, "Ava"), (2, ""), (3, "Unknown")]
finally:
    spark.stop()

This expression builds a plan. The example's collect() is the visible action that evaluates it. If blank strings should count as missing, trim and convert them to NULL explicitly before coalesce; state that policy in the data contract. For floating-point columns, handle NaN separately with isnan or nanvl when the domain treats it as missing.

Keep the latest row per key deterministically

Use a window when one row must win per key. Sort by the business timestamp, then by enough stable keys to make the ordering total. This example places NULL timestamps last and uses a unique event_id to break timestamp ties. When all timestamps for a key are NULL, the greatest event_id wins.

from datetime import datetime, timezone

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

schema = T.StructType(
    [
        T.StructField("customer_id", T.StringType(), nullable=False),
        T.StructField("event_id", T.LongType(), nullable=False),
        T.StructField("updated_at", T.TimestampType(), nullable=True),
        T.StructField("payload", T.StringType(), nullable=True),
    ]
)
rows = [
    ("a", 10, datetime(2025, 1, 1, tzinfo=timezone.utc), "old"),
    ("a", 11, datetime(2025, 1, 2, tzinfo=timezone.utc), "tie-1"),
    ("a", 12, datetime(2025, 1, 2, tzinfo=timezone.utc), "tie-2"),
    ("a", 13, None, "missing-time"),
    ("b", 20, None, "missing-time-1"),
    ("b", 21, None, "missing-time-2"),
]

spark = (
    SparkSession.builder.master("local[1]")
    .appName("pysparky-cookbook-latest-row")
    .config("spark.ui.enabled", "false")
    .config("spark.sql.session.timeZone", "UTC")
    .getOrCreate()
)
try:
    events = spark.createDataFrame(rows, schema)
    rank_column = "__pysparky_row_number"
    if rank_column in events.columns:
        raise ValueError(f"input already contains reserved column {rank_column!r}")

    latest_order = Window.partitionBy("customer_id").orderBy(
        F.col("updated_at").desc_nulls_last(),
        F.col("event_id").desc(),
    )
    latest = (
        events.withColumn(rank_column, F.row_number().over(latest_order))
        .filter(F.col(rank_column) == 1)
        .drop(rank_column)
    )
    actual = [
        (row.customer_id, row.event_id)
        for row in latest.orderBy("customer_id").select("customer_id", "event_id").collect()
    ]
    assert actual == [("a", 12), ("b", 21)]
finally:
    spark.stop()

The temporary rank column must not collide with an input field; choose a reserved name for the application or fail clearly as above. Partitioning and ordering a window can require a shuffle and sort when an action evaluates the plan. Inspect explain() and measure representative data. Do not substitute dropDuplicates(["customer_id"]) when the business rule says which row wins; that call does not define the selected row's timestamp or tie-breaker.

Clean array values with higher-order functions

Use Spark's filter and transform for element-wise array work that fits their expression model. This recipe removes NULL elements, trims each remaining string, and uppercases it. A NULL array remains NULL, an empty array remains empty, and a whitespace-only string becomes an empty string.

from pyspark.sql import SparkSession, functions as F, types as T

schema = T.StructType(
    [
        T.StructField("id", T.StringType(), nullable=False),
        T.StructField(
            "raw_tags",
            T.ArrayType(T.StringType(), containsNull=True),
            nullable=True,
        ),
    ]
)
rows = [
    ("some", [" PySpark ", None, "Spark"]),
    ("empty", []),
    ("null", None),
    ("blank", ["   "]),
]

spark = (
    SparkSession.builder.master("local[1]")
    .appName("pysparky-cookbook-array-cleanup")
    .config("spark.ui.enabled", "false")
    .getOrCreate()
)
try:
    source = spark.createDataFrame(rows, schema)
    result = source.withColumn(
        "tags",
        F.transform(
            F.filter(F.col("raw_tags"), lambda tag: tag.isNotNull()),
            lambda tag: F.upper(F.trim(tag)),
        ),
    )
    actual = [
        (row.id, row.tags)
        for row in result.orderBy("id").select("id", "tags").collect()
    ]
    assert actual == [
        ("blank", [""]),
        ("empty", []),
        ("null", None),
        ("some", ["PYSPARK", "SPARK"]),
    ]
finally:
    spark.stop()

This keeps the operation in Spark SQL expressions and adds no Python UDF. Both higher-order functions are transformations; the test's collect() is the action. If the desired contract also removes blank strings, add that predicate explicitly. Keep a Python UDF only when the behavior cannot reasonably be expressed with the available Spark functions.

References