Featured Article

Pyspark When Function Example Tutorial With Code Snippets

Kenneth Jul 13, 2026

When it comes to big data processing, Apache Spark provides a powerful and flexible interface with its Spark APIs, one of which is the Pyspark API. Pyspark is a Python library for Spark that enables data processing using Python. A vital component of Pyspark is its ability to work with dataframes and perform operations using the DataFrame API. The `when` function in Pyspark is an essential tool that allows for conditional transformations on DataFrames, which is the topic we'll explore in detail here.

PySpark Window Functions
PySpark Window Functions

The `when` function in Pyspark is particularly useful when you want to apply different transformations based on a certain condition. It's especially handy when you're dealing with large datasets and want to perform selective transformations efficiently. In this article, we'll provide examples and dig deep into how you can effectively use the `when` function in Pyspark for your data processing needs.

PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}
PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}

Understanding the `when` Function in Pyspark

The `when` function in Pyspark is a part of the `pyspark.sql.functions` module. It accepts two arguments: a predicate (a boolean expression) and an expression to be evaluated if the predicate is true. If the predicate is false, the result will be the expression provided as the default value.

PySpark “when otherwise” usage with example
PySpark “when otherwise” usage with example

Here's the basic syntax of the `when` function: ```python from pyspark.sql.functions import when df.withColumn("newCol", when(condition, trueExpression).otherwise(falseExpression)) ```

Syntax and Arguments

PySpark random sample
PySpark random sample

The `when` function follows this syntax: ```python when(predicate, trueExpression) ``` Where:

  • predicate is a boolean expression that evaluates to a boolean value (true or false).
  • trueExpression is an expression that will be evaluated if the predicate is true.

Additionally, the `when` function can include an optional otherwise clause to provide a default value when the predicate is false:

pyspark when function example
pyspark when function example

`otherwise(falseExpression)`

Example: Replacing Values Based on Conditions

Let's consider a simple example to illustrate the use of the `when` function. Suppose we have a DataFrame with a 'status' column that contains 'success', 'failure', and 'error'. We want to replace 'failure' and 'error' with 'Failed' and the rest with 'Success'.

Day 7 of #100DaysOfPyTorch  Today we learned how to save and load PyTorch models, which is crucial for real-world projects.  Step-by-step:  1️⃣ state_dict: Contains all model parameters like weights and biases.  2️⃣ Saving: Use torch.save(model.state_dict(), filename) to store parameters.  3️⃣ Loading: Create a new model instance and load parameters using load_state_dict.  4️⃣ Evaluation mode: Use .eval() for inference to disable dropout/batchnorm effects.  5️⃣ Use case: Resume training, shar... How To Start With Pytorch, Pytorch Logo, Python Range Function Tutorial, Python Code For Deploying Model, Machine Learning Model Evaluation Python, Python Range Function Explanation, Leet Code, Torch.nn Module Python, Python Range Function Guide
Day 7 of #100DaysOfPyTorch Today we learned how to save and load PyTorch models, which is crucial for real-world projects. Step-by-step: 1️⃣ state_dict: Contains all model parameters like weights and biases. 2️⃣ Saving: Use torch.save(model.state_dict(), filename) to store parameters. 3️⃣ Loading: Create a new model instance and load parameters using load_state_dict. 4️⃣ Evaluation mode: Use .eval() for inference to disable dropout/batchnorm effects. 5️⃣ Use case: Resume training, shar... How To Start With Pytorch, Pytorch Logo, Python Range Function Tutorial, Python Code For Deploying Model, Machine Learning Model Evaluation Python, Python Range Function Explanation, Leet Code, Torch.nn Module Python, Python Range Function Guide

Here's how you can do it: ```python from pyspark.sql.functions import when df = spark.createDataFrame([("success",), ("failure",), ("error",)], ["status"]) df.withColumn("result", when((df.status == "failure") | (df.status == "error"), "Failed") .otherwise("Success")) ```

In this example, the `when` function checks if the 'status' is either 'failure' or 'error'. If true, it replaces the value with 'Failed'; otherwise, it replaces it with 'Success'.

Introduction to PyTorch - A Simple Yet Powerful Deep Learning Library
Introduction to PyTorch - A Simple Yet Powerful Deep Learning Library
pyspark when function example
pyspark when function example
Technology, Train
Technology, Train
pyspark when function example
pyspark when function example
a rundown on functions
a rundown on functions
a diagram showing how to use the calculator
a diagram showing how to use the calculator
an image of different functions in the graphing function for fractions and exponents
an image of different functions in the graphing function for fractions and exponents
Top 20 Python Practice Problems for Placements | Must Solve Before Coding Interviews
Top 20 Python Practice Problems for Placements | Must Solve Before Coding Interviews
7 Power Pivot Hacks You Don’t Want To Miss
7 Power Pivot Hacks You Don’t Want To Miss

Converting Data Types Using `when` Function

The `when` function can also be used to convert data types. It's especially useful when your dataset contains inconsistent data types in a column.

Example: Converting String to Integer

Suppose you have a DataFrame where a numeric column is of string type. To convert it to an integer, you can use the `when` function with `astype()` function:

`df.withColumn("newCol", when(condition, func(df.colName.cast("int"))).otherwise(df.colName))`

Example: Converting Null Values

Here's an example of converting null values to a default value using `when`: ```python from pyspark.sql.functions import col df.withColumn("newCol", when(col("colName").isNull(), "defaultValue").otherwise(col("colName"))) ``` In this case, if the value in 'colName' is null, it will be replaced with 'defaultValue'; otherwise, it remains the same.

Chaining `when` Functions for Complex Conditions

You can chain `when` functions to build complex conditions. To do this, you use the `.otherwise` method to specify what should happen if the previous condition is not met: ```python df.withColumn("newCol", when(condition1, trueExpression1) .otherwise(when(condition2, trueExpression2) .otherwise(falseExpression))) ``` In this code, if `condition1` is true, `newCol` will be set to `trueExpression1`. If not, `newCol` will be set to the result of the nested `when` function, which follows the same logic.

Keep in mind that each condition in the chain should return the same data type to avoid casting issues.

In conclusion, the `when` function in Pyspark is a powerful tool that allows for conditional transformations on DataFrames. By mastering its use, you can significantly enhance your data processing workflows and make them more efficient. Always remember to test your conditions thoroughly and ensure your column data types are consistent to avoid potential issues. Now go ahead, and harness the power of `when` in your Pyspark journey!