Spark is a robust processing engine by Apache that allows for parallel data processing. One of its powerful features is the ability to define User-Defined Functions (UDFs), which can operate on DataFrames andıpDataFrames with multiple columns. Today, we'll explore an example of applying UDFs to multiple columns in PySpark.

Before diving in, ensure you have a basic understanding of PySpark, DataFrames, and UDFs. This will help you follow along smoothly. Let's begin.

Defining User-Defined Functions (UDFs)
UDFs are a way to incorporate custom functionality into PySpark operations. They allow us to use code not natively supported by PySpark, like complex mathematical equations, string manipulations, or machine learning models.

First, let's import necessary modules and create a simple DataFrame with multiple columns.
Import Modules and Create DataFrame

```python from pyspark.sql import functions as F, SparkSession from pyspark.sql.types import DoubleType spark = SparkSession.builder.appName('udf_example').getOrCreate() ```
Let's create a DataFrame named 'df' with three columns: 'Name', 'Age', and 'Salary'.
Create DataFrame with Multiple Columns

```python data = [('John', 30, 50000), ('Jane', 25, 55000), ('Jim', 35, 60000)] Schema = ['Name', 'Age', 'Salary'] df = spark.createDataFrame(data, Schema) df.show() ```
Applying UDFs to Multiple Columns
UDFs can take multiple input columns and return a single output column. Let's define a UDF that calculates annualSalary by multiplying 'Salary' by 12.

To use this UDF in PySpark, register it as a UDF and apply it to the 'Salary' column.
Define and Register UDF









```python annualSalary = F.udf(lambda x: x*12, returnType=DoubleType()) df = df.withColumn('AnnualSalary', annualSalary('Salary')) ```
To apply it to multiple columns, we need to wrap multiple UDF applications in a single function and apply them within the same withColumn call.
Applying UDF to Multiple Columns
Let's define another UDF that ages the 'Age' column by a specific amount, say 5 years.
```python age_old = F.udf(lambda x: x+5, returnType=DoubleType()) df = df.withColumn('Age_New', age_old('Age')) df.show() ```
Here, we used the 'withColumn' function to add a new column 'Age_New' to our DataFrame.
In PySpark, UDFs can significantly enhance the functionality of DataFrames and Datasets, making data processing tasks more efficient and enabling complex operations that wouldn't otherwise be possible. Mastering UDFs can open up a world of possibilities in data transformation, manipulation, and analysis.
Explore more cases and expand your skills with PySpark UDFs. Practice makes progress! Now that you've seen how to create and use UDFs on multiple columns, you can apply these techniques to your own projects and take your data processing capabilities to the next level.