coalesce() in PySpark

In PySpark, coalesce() from pyspark.sql.functions returns the first value that is not null from a list of columns, row by row. It is the standard way to fall back from one column to another, for example a work email, then a home email, then a fixed default. PySpark also has a DataFrame method with the same name, df.coalesce(n), which reduces the number of partitions and has nothing to do with nulls.

How coalesce() works

F.coalesce(col1, col2, ...) looks at the columns from left to right and returns the first one that is not null for each row. If every argument is null, the result is null. Arguments can be column names, Column expressions or literals, so F.coalesce('work_email', 'home_email', F.lit('unknown')) always returns a value because the literal is never null. The columns should share a data type; Spark casts compatible types to a common one.

coalesce() vs fillna()

fillna() (also called na.fill) replaces nulls in a column with a constant, for example df.fillna({'city': 'unknown'}). coalesce() is more flexible: the replacement can come from another column, and it builds a new column rather than overwriting one. Use fillna() for a fixed default across one or many columns, and coalesce() when the fallback is another column or a chain of columns.

The other coalesce: DataFrame.coalesce(n)

df.coalesce(4) is a different operation with the same name. It reduces a DataFrame to 4 partitions by merging existing ones without a full shuffle, typically to write fewer output files. It does not look at null values at all. The difference between that method and repartition() is covered in the repartition vs coalesce guide.

coalesce in Spark SQL

Spark SQL has the same function: SELECT COALESCE(work_email, home_email, 'unknown') AS email FROM contacts. ifnull(a, b) and nvl(a, b) are two-argument shortcuts that behave like coalesce(a, b). Because coalesce() is a built-in expression, Spark can optimise it, which a Python UDF doing the same check cannot.

coalesce(), fillna() and DataFrame.coalesce()
QuestionF.coalesce(cols)df.fillna(value)df.coalesce(n)
What it changesValues in a new columnNulls in existing columnsNumber of partitions
Fallback can be another columnYesNo, a constant onlyNot applicable
Works on nullsYesYesNo
Causes a shuffleNoNoNo, merges partitions

Example (PySpark)

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

spark = SparkSession.builder.getOrCreate()
contacts = spark.createDataFrame(
    [(1, "a@work.com", None, "9000000001"),
     (2, None, "b@home.com", None),
     (3, None, None, None)],
    "id INT, work_email STRING, home_email STRING, phone STRING",
)

result = contacts.select(
    "id",
    F.coalesce("work_email", "home_email").alias("email"),
    F.coalesce("work_email", "home_email", "phone", F.lit("no contact")).alias("best_contact"),
)
result.show(truncate=False)

Customer 1 has a work email, customer 2 falls back to the home email, and customer 3 has nothing, so email stays null while best_contact reaches the literal default.

Run this example in the free online PySpark compiler

Expected output

+---+----------+------------+
|id |email     |best_contact|
+---+----------+------------+
|1  |a@work.com|a@work.com  |
|2  |b@home.com|b@home.com  |
|3  |NULL      |no contact  |
+---+----------+------------+

Frequently asked questions

What does coalesce do in PySpark?

pyspark.sql.functions.coalesce returns the first non-null value among its arguments for each row. DataFrame.coalesce(n) is a different method that reduces the number of partitions.

What is the difference between coalesce and fillna in PySpark?

fillna replaces nulls with a constant; coalesce can fall back to another column, or a chain of columns, before using a constant.

Does coalesce in PySpark cause a shuffle?

The coalesce function on columns works row by row and never shuffles. DataFrame.coalesce(n) also avoids a full shuffle because it merges existing partitions.

What happens if all values passed to coalesce are null?

The result is null. Add F.lit(default) as the last argument to guarantee a value.

Practice challenges

Open the free PySpark compiler · Data Engineering challenges · Data Engineering jobs

Further reading

Follow the free PySpark tutorial

Quick reference: PySpark cheat sheet with runnable examples