Featured Article

Master PySpark F When with Practical Example Guide

Kenneth Jul 13, 2026

PySpark, a python library for Apache Spark, brings the power of the distributed processing engine to the familiar world of Python programming. When working with PySpark, the 'when' function is a crucial tool for performing conditional operations in DataFrame and DataSet APIs. Let's explore some practical examples of using 'when' in PySpark.

a poster with the names and numbers of different types of data structures in red, white and
a poster with the names and numbers of different types of data structures in red, white and

Before diving into the examples, let's recall that 'when' is a transformation function that applies a user-provided function to input DataFrame whenever the given condition is true. It returns a new DataFrame after applying transformations to the original one.

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

The 'when' Function in PySpark

PySpark's 'when' function is an efficient way to create new columns based on the conditions. It's particularly useful when you want to map values to another column based on certain conditions.

PySpark Window Functions
PySpark Window Functions

In this section, we'll use a simple DataFrame to demonstrate 'when' function usage. Let's create a DataFrame with two columns: 'name' and 'age'.

Adding a New Column Based on Conditions

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

Our first example involves adding a new column, 'status', to the DataFrame. We'll set 'status' to 'Adult' if 'age' is greater than or equal to 18, and 'Minor' otherwise.

Here's how you can do it:

```python from pyspark.sql import functions as F df = spark.createDataFrame([('Alice', 15), ('Bob', 20), ('Charlie', 17)], ['name', 'age']) df = df.withColumn('status', F.when(df['age'] >= 18, 'Adult').otherwise('Minor')) ```

Changing the Value of Existing Columns

PyTorch Cheat Sheet
PyTorch Cheat Sheet

In this example, we'll change the values of 'age' in the DataFrame. If the 'age' is less than 18, we'll replace it with 'Underage'.

Let's modify the previous DataFrame:

```python df = df.withColumn('age', F.when(df['age'] < 18, 'Underage')) ```

'when' Function with 'otherwise' for Improved Readability

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

The 'when' function in PySpark also accepts an 'otherwise' function as its second argument. This makes the code more readable, especially when dealing with multiple conditions.

Let's see this in action with a new DataFrame containing 'grade' column.

PySpark SparkConf - Attributes and Applications - DataFlair
PySpark SparkConf - Attributes and Applications - DataFlair
PySpark Drop Rows with NULL or None Values
PySpark Drop Rows with NULL or None Values
PySpark “when otherwise” usage with example
PySpark “when otherwise” usage with example
Pandas, Dask or PySpark? What Should You Choose for Your Dataset?
Pandas, Dask or PySpark? What Should You Choose for Your Dataset?
What is a DAG in Spark or PySpark - Spark by {examples}
What is a DAG in Spark or PySpark - Spark by {examples}
PySpark Groupby Explained with Example
PySpark Groupby Explained with Example
PySpark ArrayType Column With Examples
PySpark ArrayType Column With Examples
PySpark Random Sample with Example
PySpark Random Sample with Example
PySpark Tutorial for Beginners
PySpark Tutorial for Beginners

Mapping Grades with 'when' and 'otherwise'

Here, we'll map 'grade' to 'A', 'B', 'C', or 'D' based on 'age'.

Let's add this new column:

```python df = spark.createDataFrame([('John', 16, 'good'), ('Jane', 22, 'bad'), ('Jim', 30, 'ok')], ['name', 'age', 'mood']) df = df.withColumn('grade', F.when(df['age'] < 18, 'D') .when(df['age'] <= 20, 'C') .when(df['age'] <= 25, 'B') .otherwise('A')) df.show() ```

In this final example, we used 'when' with 'otherwise' for more complex conditions. It's a clean and straightforward way to handle multi-condition scenarios.

Mastering the 'when' function in PySpark will greatly enhance your ability to manipulate DataFrames based on conditions. With practice, you'll find that the 'when' function is a powerful tool that makes PySpark both efficient and enjoyable to use. Happy data processing!