Pyspark SQL's case when statement is a powerful tool for conditional processing, enabling you to define different actions based on data characteristics. By leveraging this functionality, you can streamline data transformations, perform complex calculations, and create more efficient Spark SQL operations.

In this comprehensive guide, we will delve into the intricacies of Pyspark SQL's case when example, providing a step-by-step approach to understand and implement it effectively. Mastering case when in Pyspark SQL will not only enhance your skills but also boost the efficiency of your data processing tasks.

Understanding Case When in PySpark SQL
Before exploring the Pyspark SQL case when example, let's first understand the basics of case when. It is a SQL construct that allows you to evaluate different expressions based on specified conditions. In PySpark, you can integrate case when statements into your DataFrame and Dataset APIs for data manipulation.

Case when follows a simple syntax: `CASE WHEN condition1 THEN result1 ELSE result2 END`. It provides a flexible way to handle conditions where the output depends on various data values. Now, let's dive into PySpark SQL case when examples to illustrate its usage effectively.
Basic Case When in PySpark SQL

Let's begin with a basic case when in PySpark SQL. Consider a DataFrame containing an 'Age' column. We want to categorize individuals into 'Minor', 'Adult', or 'Senior' based on their age. Here's how you can achieve this:
from pyspark.sql import functions as F
df = spark.createDataFrame([(15,), (25,), (65,)], ['Age'])
df.withColumn('Category',
F.when(F.col('Age') < 18, 'Minor')
.when(F.col('Age') < 60, 'Adult')
.otherwise('Senior')).show()
In this Pyspark SQL case when example, we used the DataFrame's withColumn function in conjunction with PySpark's when and otherwise functions to create a new 'Category' column based on the defined conditions.
Nested Case When in PySpark SQL

In some scenarios, you might need to nest case when statements to create complex conditional expressions. Let's extend the previous example to create an additional 'Discount' column based on the 'Category' and 'Age' columns.
df = df.withColumn('Discount',
F.when(F.col('Category') == 'Minor', F.lit(20))
.when(F.col('Age') >= 60, F.lit(15))
.otherwise(F.lit(0))).show()
In this nested case when example, we first checked the 'Category'. If it's 'Minor', we applied a 20% discount. If not, we then checked the 'Age'. If it's 60 or above, we applied a 15% discount. If none of the conditions were met, we applied a 0% discount.
Case When with If and Elseif Conditions

In some cases, you might want to use multiple conditions with 'if-elseif' logic instead of the nested case when approach. PySpark SQL provides the `F.expr` function to achieve this. Let's create a DataFrame with 'Income' and 'Student' columns, and calculate 'Tax' based on income and student status.
For non-students, we'll apply a graduated tax rate: no tax for income up to $20,000, 10% for income between $20,000 and $50,000, and 20% for income over $50,000. For students, the tax rate will be 5% for all incomes.








Creating Custom Conditions with 'if-elseif'
To implement this in PySpark SQL, we'll use 'if-elseif' logic with the `F.expr` function:
df = spark.createDataFrame([(15000, False), (40000, True), (70000, False)], ['Income', 'Student'])
df.withColumn('Tax',
F.expr("""
CASE
WHEN Student THEN Income*0.05
WHEN Income <= 20000 THEN 0
WHEN Income <= 50000 THEN Income*0.1
ELSE Income*0.2
END
""")).show()
In this Pyspark SQL case when example, we created a custom case when statement with multiple conditions using 'if-elseif' logic to calculate the 'Tax' column.
Case When with User-Defined Functions (UDFs)
Sometimes, you might need to use case when in conjunction with user-defined functions (UDFs) to create more complex conditional expressions. To illustrate this, let's create a UDF to categorize 'Income' into 'Low', 'Medium', or 'High' based on defined thresholds.
We'll then use this UDF within a case when statement to create a new 'Tax_Step' column. For 'Low' income, the tax rate is 0%; for 'Medium', it's 10%; and for 'High', it's 20%.
Creating UDFs for Complex Case When Expressions
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
@udf(returnType=StringType())
def income_category(income):
if income <= 20000:
return 'Low'
elif income <= 50000:
return 'Medium'
else:
return 'High'
df = df.withColumn('Income_Category', income_category('Income')) \
.withColumn('Tax_Step',
F.expr("""
CASE
WHEN Income_Category = 'Low' THEN Income*0.0
WHEN Income_Category = 'Medium' THEN Income*0.1
ELSE Income*0.2
END
""")).show()
In this Pyspark SQL case when example, we first created a UDF to categorize income. We then used this UDF within another case when statement to calculate the 'Tax_Step' column based on the income category.
Mastering Pyspark SQL's case when statements allows you to create complex conditional logic easily, enhancing your data processing capabilities. By understanding the basics and exploring various use cases, you can efficiently handle data transformation tasks and optimize your PySpark workflows. Embrace the power of case when and continue exploring the riches of PySpark SQL functionality to unleash your data processing potential.