Featured Article

Master PySpark Case When with Practical Examples and Code Snippets

Kenneth Jul 13, 2026

In the dynamic world of big data processing, Apache Spark's Python API, PySpark, offers a powerful and user-friendly interface. When working with PySpark, it's crucial to understand how to handle and manipulate data, and one such scenario involves the usage of `case when` statements. This article will delve into PySpark's `case when` example, ensuring a comprehensive understanding and providing practical insights.

PySpark Internals - Spark
PySpark Internals - Spark

Before we dive into the `case when` example, let's briefly recap PySpark's data processing capabilities. PySpark allows for in-memory computations, enabling users to perform complex operations on large datasets efficiently. It provides a rich set of higher-level abstractions, including DataFrames and Datasets, to represent structured data.

Data Science Tutorials | DataCamp Blogs
Data Science Tutorials | DataCamp Blogs

Introducing `case when` in PySpark

PySpark's `case when` statement is analogous to the SQL `CASE` statement. It allows for conditional expressions, enabling you to return different output values based on specific conditions. This is particularly useful when transforming data, such as adding salaries to a 'high', 'medium', or 'low' tier based on the actual salary.

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

To illustrate this, let's consider a simple example. Suppose we have a DataFrame, `df`, with a column 'salary' that contains employees' salaries. We want to create a new column 'salary_tier' that categorizes salaries into 'low', 'medium', and 'high'.

Basic `case when` example

pyspark case when example
pyspark case when example

Here's a basic example of using `case when` in PySpark:

```python from pyspark.sql.functions import col, when, otherwise df = df.withColumn( 'salary_tier', when(col('salary') < 50000, 'low') .when(col('salary') >= 50000 and col('salary') < 100000, 'medium') .otherwise('high') ) ```

In this example, `when()` and `otherwise()` functions are used to create conditional statements. First, it checks if the 'salary' is less than 50000; if true, it assigns 'low'. Next, it checks if the salary is between 50000 (inclusive) and 100000 (exclusive); if true, it assigns 'medium'. If neither condition is met, `otherwise()` assigns 'high'.

After running this code, the new column 'salary_tier' will be added to the DataFrame `df`.

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

Nested `case when` example

You can also nest `case when` statements to create more complex conditional expressions. Let's expand the previous example to include an additional tier for 'very high' salaries:

```python df = df.withColumn( 'salary_tier', when(col('salary') < 50000, 'low') .when(col('salary') >= 50000 and col('salary') < 100000, 'medium') .when(col('salary') >= 100000, 'high') .otherwise('very high') ) ```

In this updated example, we've added a new condition to check if the 'salary' is 100000 or more. If true, it assigns 'high'. If none of the previous conditions are met, it assigns 'very high'.

pyspark mapreduce - Google Search Computer Coding, Google Search, Computer, Science, Coding
pyspark mapreduce - Google Search Computer Coding, Google Search, Computer, Science, Coding

The updated DataFrame now includes an additional tier for exceptionally high salaries.

Advanced use-cases with `case when`

PySpark Fensterfunktionen Spickzettel
PySpark Fensterfunktionen Spickzettel
PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}
PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}
a diagram showing the different types of agent skills and how they are used to help them
a diagram showing the different types of agent skills and how they are used to help them
PyTorch Cheat Sheet
PyTorch Cheat Sheet
#tcs #dataengineer #dataengineering #pyspark #azuredatafactory #deltalake #sql #bigdata #interviewpreparation #careergrowth #techcareers | Kushboo Chauhan
#tcs #dataengineer #dataengineering #pyspark #azuredatafactory #deltalake #sql #bigdata #interviewpreparation #careergrowth #techcareers | Kushboo Chauhan
PySpark Tutorial for Beginners
PySpark Tutorial for Beginners
Beginner's Guide To Text Classification Using PyCaret
Beginner's Guide To Text Classification Using PyCaret
a notebook with some writing on it and an image of a computer working diagram in the middle
a notebook with some writing on it and an image of a computer working diagram in the middle
Client Challenge
Client Challenge

PySpark's `case when` statements can also be used in conjunction with other functions and operations to create more advanced data transformations. For instance, you can use `case when` to control the aggregation of data. Let's suppose we want to find the minimum, maximum, and average salary for each salary tier.

To achieve this, we can use the `groupBy` method along with `agg` function to aggregate the data. Within the `agg` function, we can use `case when` to separate the data based on salary tiers:

```python from pyspark.sql.functions import avg, max, min, col, when, otherwise agg_df = df.groupBy('salary_tier').agg( min('salary').alias('min_salary'), avg('salary').alias('avg_salary'), max('salary').alias('max_salary') ) ```

This code groups the data by 'salary_tier' and calculates the minimum, average, and maximum salaries within each tier. The resulting DataFrame `agg_df` contains the aggregated data.

By utilizing the `case when` statement, you can create complex data transformations and perform intricate data analysis using PySpark.

In the realm of big data processing, mastering `case when` statements in PySpark opens up a wealth of possibilities. From simple data transformations to advanced aggregations, these conditional expressions empower you to manipulate and analyze data more effectively. By continually exploring and experiment with these functionalities, you'll be well on your way to harnessing the full potential of PySpark for your big data needs.