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 C
Quick Check:
substring start=1, length=5 extracts 'Spark' [OK]
Hint: substring uses 1-based start index [OK]
Common Mistakes:
Assuming 0-based index for substring
Extracting wrong number of characters
Confusing substring with slice
4. Identify the error in this Spark code that tries to replace all spaces with underscores in column text:
from pyspark.sql.functions import regexp_replace df.select(regexp_replace(text, ' ', '_')).show()
medium
A. Incorrect number of arguments to regexp_replace
B. Missing column reference using col()
C. Wrong function name, should be replace()
D. Using show() instead of collect()
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()
Use regexp_replace(col('text'), ' ', '_') to refer to the column properly.
Final Answer:
Missing column reference using col() -> Option B
Quick Check:
Use col() to reference columns in functions [OK]
Hint: Always wrap column names with col() in functions [OK]
Common Mistakes:
Passing column name as string without col()
Confusing regexp_replace with replace
Ignoring function argument requirements
5. You want to create a new column 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?
hard
A. df.withColumn('clean_name', regexp_replace(lower(trim(col('name'))), '\\d', ''))
B. df.withColumn('clean_name', lower(trim(regexp_replace(col(name), '\\d', ''))))
C. df.withColumn('clean_name', trim(lower(regexp_replace(col(name), '\\d', ''))))
D. df.withColumn('clean_name', trim(regexp_replace(lower(col(name)), '\\d', '')))
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 A