Featured Article

Master PySpark UDF Function Example with Code

Kenneth Jul 13, 2026

Apache Spark's Python API, PySpark, provides a powerful way to execute parallel operations on large datasets. Sometimes, you need to apply custom functions to these datasets, necessitating User-Defined Functions (UDFs). UDFs allow you to insert your custom Python code into Spark computations, extending Spark's functionality. Let's explore an example of creating a PySpark UDF function.

pyspark udf function example
pyspark udf function example

Consider a scenario where you have a DataFrame with timestamps in 'yyyy-MM-dd HH:mm:ss' format, and you want to extract the day of the week. Here's how you would create a UDF for this:

PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}
PySpark 4.0 Tutorial For Beginners with Examples - Spark By {Examples}

Creating and Registering a PySpark UDF

Before we proceed, ensure you've imported required modules and set up a SparkSession:

pyspark udf function example
pyspark udf function example

```python from pyspark.sql import functions as F from pyspark.sql.functions import udf from pyspark.sql.types import * from datetime import datetime from dateutil import parser from pyspark.sql import SparkSession spark = SparkSession.builder\AppName("UDFExample").getOrCreate() ```

Defining the UDF

First, define your UDF by converting your Python function into a UDF. In this case, we'll use the 'dateutil' library to parse the timestamp and extract the day of the week:

a poster with the words python for everything written in different languages and numbers on it
a poster with the words python for everything written in different languages and numbers on it

```python def get_day_of_week(date_str): dt = parser.parse(date_str) return dt.strftime('%A') get_day_of_week_udf = udf(get_day_of_week, StringType()) ```

Using the UDF in a DataFrame

Now, apply the UDF to your DataFrame:

```python df = spark.range(10) df = df.withColumn('timestamp', F.lit('2022-06-01 12:00:00')) df = df.withColumn('day_of_week', get_day_of_week_udf('timestamp')) df.show() ```

This will create a new DataFrame column 'day_of_week', containing the day of the week for each row.

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

.Registering a PySpark UDF for Use in SQL Statements

Sometimes, you might want to use the UDF in SQL statements. To do this, you'll need to register the UDF:

```python df.createOrReplaceTempView("tempview") spark.sql("SELECT get_day_of_week(timestamp) FROM tempview").show() ```

Using the Registered UDF in a Select Expression

pyspark udf function example
pyspark udf function example

Now, you can use the registered UDF just like any other function in SQL:

```python df2 = df.withColumn('day_of_week_sql', F.expr("get_day_of_week(timestamp)")) df2.show() ```

The resulting DataFrame 'df2' should have the same 'day_of_week' column as 'df', plus an extra 'day_of_week_sql' column demonstrating how to use the UDF in a 'SELECT' expression.

Python Functions | def function | How to Create Python Functions?⋆
Python Functions | def function | How to Create Python Functions?⋆
Using the implode function in PHP
Using the implode function in PHP
All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)
Mastering PySpark Joins, Filters, and GroupBys: A Comprehensive Guide
Mastering PySpark Joins, Filters, and GroupBys: A Comprehensive Guide
pydash: Functional Programming in Python Made Easy
pydash: Functional Programming in Python Made Easy
a rundown on functions
a rundown on functions
graphing and exponental functions poster
graphing and exponental functions poster
Learn how to use PHP's in_array() Function
Learn how to use PHP's in_array() Function
Php is a programming language ✨
Php is a programming language ✨

In the world of big data processing, UDFs provide immense flexibility. They allow you to incorporate your domain-specific knowledge into Spark computations, enhancing their power and scope. Hence, mastering UDFs is a crucial aspect of becoming proficient in PySpark.