Featured Article

Mastering PySpark When Function A Complete Guide to Conditional Logic in pyspark sql functions import when

Kenneth Jul 13, 2026

When working with PySpark's DataFrame API, the need often arises to apply conditional transformations to the data. This is where the `when` function from `pyspark.sql.functions` comes into play. This function allows you to perform conditional operations on DataFrame columns, similar to SQL's `CASE` statement, making data manipulation tasks more straightforward.

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

In order to use `when`, you need to import it from `pyspark.sql.functions`. Here's a simple example illustrating its usage:

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

Understanding PySpark's `when` Function

The `when` function takes two parameters: a boolean expression and a value. If the boolean expression is true, the function returns the specified value; otherwise, it returns `None`.

a cell phone with the text postgresql and other information on it
a cell phone with the text postgresql and other information on it

Let's consider a simple DataFrame with a 'Grade' column, where values are 'A', 'B', or 'C'. We'll use `when` to create a new column, 'Points', which represents the numerical value of each grade.

Basic Usage of `when`

SQL String Functions and Pattern Matching
SQL String Functions and Pattern Matching

Here's a simple example of using `when` to map grades to points:

from pyspark.sql.functions import when, col df = spark.createDataFrame([('A',), ('B',), ('C',)], ['Grade']) df.withColumn('Points', when(col('Grade') == 'A', 5).otherwise(0)).show()

The `otherwise` function is used to provide a default value when the condition is not met. In this example, when the 'Grade' is 'A', the 'Points' column will contain 5; otherwise, it will contain 0.

Combining Multiple Conditions

SQL in 60 days
SQL in 60 days

You can also chain multiple `when` conditions to create complex conditional transformations. The following example maps grades 'A', 'B', and 'C' to points 5, 3, and 1, respectively, and maps any other value to 0:

df.withColumn('Points', when(col('Grade') == 'A', 5).when(col('Grade') == 'B', 3).otherwise(1)).show()

Applying Conditions Based on Column Values

In many use cases, you'll want to apply conditions based on the values of multiple columns. In such cases, you can still use `when`, but you'll need to create the conditions using the DataFrame's column values.

7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio

For instance, consider a DataFrame with 'Age' and 'Grade' columns. We want to give bonus points to students who are 18 and older and have a grade of 'A'. We can achieve this using the following code:

df.withColumn('Bonus', when(col('Grade') == 'A' & col('Age') >= 18, 2).otherwise(0)).show()

Using `when` with UDFs

Transform Single Inputs into Tables Using PySpark UDTFs
Transform Single Inputs into Tables Using PySpark UDTFs
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
from pyspark.sql.functions import when
from pyspark.sql.functions import when
SQL Cheat Sheet in 60 seconds 👇
SQL Cheat Sheet in 60 seconds 👇
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
SQL Query Execution Order
SQL Query Execution Order
Understanding window functions in SQL
Understanding window functions in SQL
SQL Query Execution Order Explained | Logical Order of SQL Query Processing
SQL Query Execution Order Explained | Logical Order of SQL Query Processing

You can also use `when` in combination with User Defined Functions (UDFs) to apply complex transformations based on conditional logic. Here's an example where we create a UDF to calculate the letter grade based on a numerical score, and then use `when` to assign points based on the grade:

from pyspark.sql.functions import udf from typing import Union def letter_grade(score: Union[float, int]) -> str: if score >= 90: return 'A' elif score >= 80: return 'B' elif score >= 70: return 'C' else: return 'D' letter_grade_udf = udf(letter_grade) df.withColumn('Grade', letter_grade_udf(col('Score'))) \ .withColumn('Points', when(col('Grade') == 'A', 5).when(col('Grade') == 'B', 3).otherwise(1)).show()

This demonstrates how `when` can be used as a flexible tool to apply conditional transformations to DataFrames, from simple mapping functions to complex conditional computations involving multiple columns and UDFs.

With `when`, you can write clear, concise, and easily maintainable code for data manipulation tasks in PySpark. By chaining conditions and combining `when` with other functions, you can create powerful conditional transformations to suit your specific use cases. Happy coding!