Featured Article

Master PySpark When Function Tips and Tricks

Kenneth Jul 13, 2026

Spark's DataFrame and Dataset APIs offer powerful transformations for data processing. One of the most versatile functions is `when()`, part of the If-Else conditions provided by Spark. This function allows you to define conditional transformations based on boolean expressions, enhancing your data manipulation capabilities.

PySpark Window Functions
PySpark Window Functions

`when()` is particularly useful when you want to apply a transformation conditionally based on the data within your DataFrame or Dataset. It lets you create expressive and readable code, making your transformations more efficient and easier to understand.

There are three types of window function families 🏠
There are three types of window function families 🏠

The `when()` Syntax and Basic Usage

Before diving into the intricacies of `when()`, let's understand its basic syntax. `when()` takes two primary parameters: a boolean condition and the transformation to apply when that condition is true.

Know About Apache Spark Using PySpark for Data Engineering
Know About Apache Spark Using PySpark for Data Engineering

The basic syntax is as follows:

df.withColumn(column_name, when(condition, value_to_replace).otherwise(default_value))

Here, column_name is the name of the column you want to transform, condition is the boolean expression that determines when the transformation applies, and value_to_replace is the value that will replace the original value when the condition is true. If the condition is false, the default_value will be used.

PySpark DataFrame Transformations: select vs withColumn
PySpark DataFrame Transformations: select vs withColumn

Example: Replacing Values Based on Conditions

Here's a simple example where we replace the value in a column based on a condition:

Here, we've used `when()` to fill null values in the 'no_of_votes' column with 'Unknown'.

Get the first and last value of the month 🗓
Get the first and last value of the month 🗓

Chaining `when()` Functions

You can chain multiple `when()` functions to create complex conditional transformations:

For instance, to replace null with 'Unknown', 0 with 'Zero', and numbers less than 500 with 'Low' in the 'no_of_votes' column:

How to calculate a cumulative sum (running total) 📈
How to calculate a cumulative sum (running total) 📈

df.withColumn('no_of_votes',
                when(col('no_of_votes').isNull(), "Unknown")
                .when(col('no_of_votes') == 0, "Zero")
                .when(col('no_of_votes') < 500, "Low")
                .otherwise("$no_of_votes"))
              .show()

Applying Transformations with `when()`

`when()` can be used to apply transformations like `cast()`, `size()`, `count()`, `rank()`, and more, adding another layer of versatility to your data transformations.

How to calculate a moving average 📈
How to calculate a moving average 📈
pyspark function when
pyspark function when
Select only the most recent records! ✨
Select only the most recent records! ✨
Access previous rows with LAG window function ⏮️
Access previous rows with LAG window function ⏮️
SQL Window Functions use a sliding frame 🪟⤵
SQL Window Functions use a sliding frame 🪟⤵
pyspark function when
pyspark function when
PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}
PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}
Rank each value in your dataset 1️⃣
Rank each value in your dataset 1️⃣
pyspark function when
pyspark function when

However, remember to consider the performance implications of using complex conditions and transformations. Always aim for.balance between code readability and processing efficiency.

Using `when()` with `count()`

Here's an example of using `when()` with `count()` to create a new column with the count of null values in each row:

df.withColumn('null_count', sum(when(col(c).isNull(), 1).otherwise(0))).show()

In conclusion, `when()` is a powerful function that extends the capabilities of Spark's DataFrame and Dataset APIs. It allows you to create expressive, readable, and efficient conditional transformations. By leveraging the power of `when()`, you can enhance your data processing workflows and extract more insights from your data.