Bird
Raised Fist0
Apache Sparkdata~20 mins

UDFs (User Defined Functions) in Apache Spark - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
UDF Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple UDF application
What is the output of this Spark code that uses a UDF to square numbers in a DataFrame?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
from pyspark.sql.types import IntegerType

spark = SparkSession.builder.master('local').appName('UDF Test').getOrCreate()
data = [(1,), (2,), (3,)]
df = spark.createDataFrame(data, ['num'])

square_udf = udf(lambda x: x * x, IntegerType())
df2 = df.withColumn('square', square_udf(df['num']))
df2.show()
A
+---+------+
|num|square|
+---+------+
|  1|     1|
|  2|     4|
|  3|     9|
+---+------+
BTypeError: 'int' object is not callable
CSyntaxError: invalid syntax
D
+---+------+
|num|square|
+---+------+
|  1|     2|
|  2|     4|
|  3|     6|
+---+------+
Attempts:
2 left
💡 Hint
Think about what the lambda function does to each number.
❓ data_output
intermediate
2:00remaining
Result of UDF with string manipulation
Given this Spark code with a UDF that reverses strings, what is the resulting DataFrame output?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

spark = SparkSession.builder.master('local').appName('UDF String').getOrCreate()
data = [('apple',), ('banana',), ('cherry',)]
df = spark.createDataFrame(data, ['fruit'])

reverse_udf = udf(lambda s: s[::-1], StringType())
df2 = df.withColumn('reversed', reverse_udf(df['fruit']))
df2.show()
A
+------+--------+
| fruit|reversed|
+------+--------+
| apple|  elppa|
|banana| ananab|
|cherry| yrrehc|
+------+--------+
B
+------+--------+
| fruit|reversed|
+------+--------+
| apple|  apple|
|banana| banana|
|cherry| cherry|
+------+--------+
CTypeError: 'NoneType' object is not subscriptable
DSyntaxError: invalid syntax
Attempts:
2 left
💡 Hint
The lambda reverses the string using slicing.
🔧 Debug
advanced
2:00remaining
Identify the error in this UDF code
What error will this Spark code raise when trying to apply the UDF?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
from pyspark.sql.types import IntegerType

spark = SparkSession.builder.master('local').appName('UDF Error').getOrCreate()
data = [(1,), (2,), (3,)]
df = spark.createDataFrame(data, ['num'])

def add_five(x):
    return x + 5

add_five_udf = udf(add_five)
df2 = df.withColumn('plus_five', add_five_udf(df['num']))
df2.show()
ASyntaxError: invalid syntax
BTypeError: add_five() missing 1 required positional argument: 'x'
C
+---+---------+
|num|plus_five|
+---+---------+
|  1|        6|
|  2|        7|
|  3|        8|
+---+---------+
DAnalysisException: UDF return type must be specified
Attempts:
2 left
💡 Hint
Check how the UDF is defined and registered.
🚀 Application
advanced
2:30remaining
Using UDF to categorize ages
You want to add a new column 'age_group' to a Spark DataFrame with ages, categorizing ages as 'child' (<18), 'adult' (18-64), or 'senior' (65+). Which UDF definition and usage will produce the correct output?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

spark = SparkSession.builder.master('local').appName('Age Group').getOrCreate()
data = [(5,), (30,), (70,)]
df = spark.createDataFrame(data, ['age'])
A
age_group_udf = udf(lambda age: 'child' if age &lt; 18 else 'adult' if age &lt; 65 else 'senior', StringType())
df2 = df.withColumn('age_group', age_group_udf(df['age']))
df2.show()
B
age_group_udf = udf(lambda age: 'child' if age &lt; 18 else 'adult' if age &lt;= 64 else 'senior', StringType())
df2 = df.withColumn('age_group', age_group_udf(df['age']))
df2.show()
C
age_group_udf = udf(lambda age: 'child' if age &lt;= 18 else 'adult' if age &lt;= 65 else 'senior', StringType())
df2 = df.withColumn('age_group', age_group_udf(df['age']))
df2.show()
D
age_group_udf = udf(lambda age: 'child' if age &lt;= 18 else 'adult' if age &lt; 65 else 'senior', StringType())
df2 = df.withColumn('age_group', age_group_udf(df['age']))
df2.show()
Attempts:
2 left
💡 Hint
Check the age boundaries carefully for each group.
🧠 Conceptual
expert
1:30remaining
Why avoid UDFs when possible in Spark?
Which is the main reason to avoid using UDFs in Spark when native functions exist?
AUDFs cannot handle null values, causing runtime exceptions.
BUDFs always cause syntax errors in Spark SQL queries.
CUDFs are slower because they break Spark's optimization and serialization, causing performance loss.
DUDFs automatically convert data to Pandas DataFrames, which is inefficient.
Attempts:
2 left
💡 Hint
Think about how Spark optimizes queries and executes code.

Practice

(1/5)
1. What is the main purpose of a User Defined Function (UDF) in Apache Spark?
easy
A. To create new Spark sessions
B. To manage cluster resources
C. To optimize Spark SQL queries automatically
D. To apply custom logic to each row of a DataFrame

Solution

  1. Step 1: Understand UDF role in Spark

    A UDF lets you add your own logic to process each row in a DataFrame, beyond built-in functions.
  2. Step 2: Compare options

    The other options relate to Spark setup or optimization, not custom row logic.
  3. Final Answer:

    To apply custom logic to each row of a DataFrame -> Option D
  4. Quick Check:

    UDF = custom row logic [OK]
Hint: UDFs add your own row-wise logic in Spark [OK]
Common Mistakes:
  • Confusing UDFs with Spark session management
  • Thinking UDFs optimize queries automatically
  • Assuming UDFs manage cluster resources
2. Which of the following is the correct way to register a UDF in PySpark with a return type of IntegerType?
easy
A. spark.udf.register('my_udf', func, 'IntegerType')
B. spark.udf.register('my_udf', func)
C. spark.udf.register('my_udf', func, IntegerType())
D. spark.udf.create('my_udf', func, IntegerType())

Solution

  1. Step 1: Recall UDF registration syntax

    The correct method is spark.udf.register with function name, function, and return type as a DataType object.
  2. Step 2: Evaluate options

    spark.udf.register('my_udf', func, IntegerType()) uses IntegerType() correctly. spark.udf.register('my_udf', func) misses return type. spark.udf.create('my_udf', func, IntegerType()) uses a non-existent method. spark.udf.register('my_udf', func, 'int') uses a string instead of IntegerType().
  3. Final Answer:

    spark.udf.register('my_udf', func, IntegerType()) -> Option C
  4. Quick Check:

    Register UDF with return type object [OK]
Hint: Always specify return type as DataType object when registering UDF [OK]
Common Mistakes:
  • Omitting the return type parameter
  • Using incorrect method names like create
  • Passing return type as string instead of DataType
3. Given the following PySpark code, what will be the output of df.select('name', 'age_plus_one').show()?
from pyspark.sql.functions import udf
from pyspark.sql.types import IntegerType

def add_one(age):
    return age + 1

add_one_udf = udf(add_one, IntegerType())
df = spark.createDataFrame([('Alice', 30), ('Bob', 25)], ['name', 'age'])
df = df.withColumn('age_plus_one', add_one_udf('age'))
medium
A. [[Alice, 31], [Bob, 26]]
B. [[Alice, 30], [Bob, 25]]
C. Error: UDF missing return type
D. [[Alice, 1], [Bob, 1]]

Solution

  1. Step 1: Understand UDF logic

    The UDF adds 1 to the 'age' column values: 30 + 1 = 31, 25 + 1 = 26.
  2. Step 2: Check DataFrame transformation

    The new column 'age_plus_one' will have values 31 and 26 for Alice and Bob respectively.
  3. Final Answer:

    [[Alice, 31], [Bob, 26]] -> Option A
  4. Quick Check:

    age + 1 = 31, 26 [OK]
Hint: UDF applies function row-wise, transforming each value [OK]
Common Mistakes:
  • Forgetting to specify return type causing errors
  • Assuming original age remains unchanged
  • Confusing UDF output with input data
4. Identify the error in the following PySpark UDF code snippet:
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

def greet(name):
    return 'Hello ' + name

greet_udf = udf(greet)
df = spark.createDataFrame([('John',), ('Jane',)], ['name'])
df = df.withColumn('greeting', greet_udf('name'))
df.show()
medium
A. UDF missing return type specification
B. Function greet has wrong parameter type
C. DataFrame creation syntax is incorrect
D. withColumn method is used incorrectly

Solution

  1. Step 1: Check UDF registration

    The UDF is created without specifying the return type, which is required.
  2. Step 2: Verify other code parts

    Function parameter and DataFrame creation are correct. withColumn usage is proper.
  3. Final Answer:

    UDF missing return type specification -> Option A
  4. Quick Check:

    Always specify return type when creating UDF [OK]
Hint: Always specify return type when defining UDF [OK]
Common Mistakes:
  • Omitting return type causes runtime errors
  • Assuming return type is optional
  • Misunderstanding function parameter types
5. You want to create a UDF that returns the length of a string column but safely handles null values by returning 0 instead of failing. Which of the following UDF definitions correctly implements this behavior?
hard
A. def safe_length(s): return len(s) safe_length_udf = udf(safe_length, IntegerType())
B. def safe_length(s): if s is None: return 0 else: return len(s) safe_length_udf = udf(safe_length, IntegerType())
C. def safe_length(s): if s == '': return 0 return len(s) safe_length_udf = udf(safe_length, StringType())
D. def safe_length(s): return s.length() safe_length_udf = udf(safe_length, IntegerType())

Solution

  1. Step 1: Handle null values safely

    def safe_length(s): if s is None: return 0 else: return len(s) safe_length_udf = udf(safe_length, IntegerType()) checks if input is None and returns 0, preventing errors.
  2. Step 2: Check return type and logic

    def safe_length(s): if s is None: return 0 else: return len(s) safe_length_udf = udf(safe_length, IntegerType()) returns IntegerType and uses len(s) correctly. Others either miss null check or use wrong return type or method.
  3. Final Answer:

    def safe_length(s): if s is None: return 0 else: return len(s) safe_length_udf = udf(safe_length, IntegerType()) -> Option B
  4. Quick Check:

    Check nulls first, then return length [OK]
Hint: Check for None before calling len() in UDF [OK]
Common Mistakes:
  • Not handling None causing runtime errors
  • Returning wrong data type from UDF
  • Using string methods incorrectly in Python
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard