String functions help you change and analyze text data easily in Spark. They make working with words and sentences simple.
String functions in Spark in Apache Spark
from pyspark.sql.functions import lower, upper, trim, length, substring, concat, instr, regexp_replace # Example usage in select: df.select(lower(df.column_name), upper(df.column_name), trim(df.column_name))
from pyspark.sql.functions import lower df.select(lower(df.name))
from pyspark.sql.functions import trim df.select(trim(df.address))
from pyspark.sql.functions import substring df.select(substring(df.name, 1, 3))
from pyspark.sql.functions import regexp_replace df.select(regexp_replace(df.comment, 'bad', 'good'))
This program creates a small table with names and comments. It then uses many string functions to clean names, change case, measure comment length, get parts of comments, replace spaces with underscores, find the word 'Spark', and create a user ID by joining text.
from pyspark.sql import SparkSession from pyspark.sql.functions import lower, upper, trim, length, substring, concat, instr, regexp_replace spark = SparkSession.builder.appName('StringFunctionsExample').getOrCreate() data = [ (1, ' Alice ', 'Hello World!'), (2, 'Bob', 'Spark is fun'), (3, 'Charlie', ' Data Science ') ] columns = ['id', 'name', 'comment'] df = spark.createDataFrame(data, columns) # Use string functions result = df.select( trim(df.name).alias('trimmed_name'), lower(trim(df.name)).alias('lower_name'), upper(trim(df.name)).alias('upper_name'), length(df.comment).alias('comment_length'), substring(df.comment, 1, 5).alias('comment_start'), regexp_replace(df.comment, ' ', '_').alias('comment_no_spaces'), instr(df.comment, 'Spark').alias('spark_pos'), concat(trim(df.name), '_user').alias('user_id') ) result.show()
String functions in Spark work on columns, so always use them inside DataFrame operations.
Remember to import functions from pyspark.sql.functions before using them.
Some functions like instr return 0 if the text is not found.
String functions help clean and analyze text data in Spark easily.
Use them inside DataFrame select or withColumn to transform text columns.
Common functions include lower, upper, trim, substring, regexp_replace, and instr.
Practice
Solution
Step 1: Understand the function purpose
Thelower()function changes all letters in a string to lowercase.Step 2: Compare with other functions
upper()makes letters uppercase,trim()removes spaces, andsubstring()extracts part of the string.Final Answer:
lower()-> Option DQuick Check:
Lowercase conversion =lower()[OK]
- Confusing lower() with upper()
- Using trim() to change case
- Thinking substring() changes case
name?Solution
Step 1: Understand Spark column referencing
In Spark, to refer to a column by name in functions, usecol('columnName').Step 2: Apply trim function correctly
Thetrim()function expects a Column object, sotrim(col('name'))is correct syntax.Final Answer:
df.select(trim(col('name'))) -> Option AQuick Check:
Use col() inside trim() for column reference [OK]
- Passing string directly without col()
- Using variable name without quotes or col()
- Using trim() without any argument
from pyspark.sql.functions import substring
df = spark.createDataFrame([('SparkData',)], ['word'])
df.select(substring('word', 1, 5).alias('sub')).collect()
Solution
Step 1: Understand substring parameters
substring('word', 1, 5)extracts 5 characters starting at position 1 (1-based index).Step 2: Extract substring from 'SparkData'
Characters 1 to 5 are 'S', 'p', 'a', 'r', 'k' forming 'Spark'.Final Answer:
[Row(sub='Spark')] -> Option CQuick Check:
substring start=1, length=5 extracts 'Spark' [OK]
- Assuming 0-based index for substring
- Extracting wrong number of characters
- Confusing substring with slice
text:from pyspark.sql.functions import regexp_replace
df.select(regexp_replace(text, ' ', '_')).show()
Solution
Step 1: Check argument types for regexp_replace
The first argument must be a Column object, not a bare identifier.Step 2: Correct usage with col()
Useregexp_replace(col('text'), ' ', '_')to refer to the column properly.Final Answer:
Missing column reference using col() -> Option BQuick Check:
Use col() to reference columns in functions [OK]
- Passing column name as string without col()
- Confusing regexp_replace with replace
- Ignoring function argument requirements
clean_name in a Spark DataFrame by trimming spaces, converting to lowercase, and replacing all digits with empty strings from column name. Which code snippet correctly does this?Solution
Step 1: Order of operations matters
First trim spaces, then convert to lowercase, then remove digits.Step 2: Check each option's function nesting
df.withColumn('clean_name', regexp_replace(lower(trim(col('name'))), '\\d', '')) trims first, then lowers, then replaces digits last, matching the required order.Final Answer:
df.withColumn('clean_name', regexp_replace(lower(trim(col('name'))), '\\d', '')) -> Option AQuick Check:
Trim -> Lower -> Replace digits = df.withColumn('clean_name', regexp_replace(lower(trim(col('name'))), '\\d', '')) [OK]
- Wrong order of function calls
- Missing col() around column name
- Incorrect regex pattern for digits
Ready to prove it?
Pass the test and this pattern moves unknown
