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.

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

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`.

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`

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

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.

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








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!