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.

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.

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.

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

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

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

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.









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!