Type casting and null handling in Apache Spark - Time & Space Complexity
When working with data in Apache Spark, converting data types and handling missing values are common tasks.
We want to understand how the time to do these tasks changes as the data grows.
Analyze the time complexity of the following code snippet.
from pyspark.sql.functions import col
# Cast column 'age' to integer and handle nulls by filling with 0
df = df.withColumn('age_int', col('age').cast('int'))
df = df.na.fill({'age_int': 0})
This code converts the 'age' column to integers and replaces any missing values with zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Spark applies the cast and null fill to each row in the dataset.
- How many times: Once per row, so the number of rows n times.
Each row is processed individually for casting and null handling.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to cast and handle nulls grows linearly with the number of rows.
[X] Wrong: "Casting a column or filling nulls happens instantly regardless of data size."
[OK] Correct: Each row must be processed, so more rows mean more work and more time.
Understanding how data transformations scale helps you write efficient Spark code and explain your reasoning clearly.
"What if we cast multiple columns and fill nulls for all of them? How would the time complexity change?"
Practice
cast() function do in Apache Spark DataFrames?Solution
Step 1: Understand the purpose of
Thecast()cast()function is used to convert the data type of a column in a Spark DataFrame to another type, such as from string to integer.Step 2: Compare with other options
Other options describe different functions: removing nulls, filtering, or sorting, which are not related to type casting.Final Answer:
It changes the data type of a column to another specified type. -> Option DQuick Check:
cast()changes type = A [OK]
- Confusing cast() with filtering or sorting functions
- Thinking cast() removes null values
- Assuming cast() modifies data content instead of type
age to integer type in Spark DataFrame?Solution
Step 1: Recall the correct cast syntax in Spark
In Spark, to cast a column, you usecolumn.cast('type'). Sodf.age.cast('int')is correct.Step 2: Check other options for syntax errors
df.select(cast(df.age, 'int')) uses cast as a function incorrectly. df.select(df.age.toInt()) uses a methodtoInt()which does not exist in Spark DataFrame columns. df.select(df.age.convert('int')) usesconvert()which is not a Spark method.Final Answer:
df.select(df.age.cast('int')) -> Option BQuick Check:
Usecolumn.cast('type')syntax = D [OK]
column.cast('type') to cast columns [OK]- Using Python native methods like toInt() on Spark columns
- Trying to use cast as a standalone function
- Using non-existent methods like convert()
from pyspark.sql.functions import col
df = spark.createDataFrame([("25",), ("30",), (None,)], ["age"])
df2 = df.select(col("age").cast("int").alias("age_int"))
df2.show()What will be the output?
Solution
Step 1: Understand casting behavior with nulls
Casting a string column with None values to integer results in integer values for valid strings and null for None values, not zero or error.Step 2: Check the output of show()
The DataFrame will display 25 and 30 as integers, and null for the None entry.Final Answer:
+-------+ |age_int| +-------+ | 25| | 30| | null| +-------+ -> Option AQuick Check:
Nulls remain null after cast = B [OK]
- Expecting None to become 0 after cast
- Thinking casting None causes error
- Confusing syntax errors with runtime behavior
salary with 0:df = df.withColumn("salary", df["salary"].cast("int").fillna(0))Solution
Step 1: Understand method chaining on Column vs DataFrame
In Spark,fillna()is a DataFrame method, not a Column method. Callingfillna()on a Column object causes an error.Step 2: Correct usage
To replace nulls after casting, usedf = df.withColumn('salary', df['salary'].cast('int'))thendf = df.fillna({'salary': 0}).Final Answer:
fillna() cannot be called on a Column object; it should be called on DataFrame. -> Option CQuick Check:
fillna() on DataFrame, not Column = C [OK]
- Calling fillna() on a Column instead of DataFrame
- Assuming cast() changes null values automatically
- Misusing withColumn() syntax
score containing numeric strings and some nulls. You want to create a new integer column score_int where nulls become -1 after casting. Which code correctly does this?Solution
Step 1: Understand null handling with casting
Casting null strings to int results in null integers. To replace nulls with -1 in the new column, usewhen()to check nulls before casting.Step 2: Analyze options
df.withColumn('score_int', when(col('score').isNull(), -1).otherwise(col('score').cast('int'))) useswhen()to assign -1 if null, else cast. Options B, C, and D try to fill nulls after casting, but fillna() or na.fill() on columns or DataFrames after casting may not replace nulls correctly or require separate steps.Final Answer:
df.withColumn('score_int', when(col('score').isNull(), -1).otherwise(col('score').cast('int'))) -> Option AQuick Check:
Use when() for conditional null replacement before cast = A [OK]
- Using fillna() on columns instead of DataFrame
- Expecting fillna() to replace nulls after cast automatically
- Not handling nulls before casting
Ready to prove it?
Pass the test and this pattern moves unknown
