Bird
Raised Fist0
Apache Sparkdata~20 mins

Type casting and null handling in Apache Spark - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Type Casting and Null Handling Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of type casting with null values in Spark DataFrame
What is the output of the following Spark code snippet?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.getOrCreate()
data = [("1", "100"), ("2", None), (None, "300")]
df = spark.createDataFrame(data, ["id", "value"])
df_cast = df.select(col("id").cast("int").alias("id_int"), col("value").cast("int").alias("value_int"))
df_cast.show()
A
+------+---------+
|id_int|value_int|
+------+---------+
|     1|      100|
|     2|     null|
|  null|      300|
+------+---------+
B
+------+---------+
|id_int|value_int|
+------+---------+
|     1|      100|
|     2|        0|
|     0|      300|
+------+---------+
CRuntimeError: Cannot cast null values to int
D
+------+---------+
|id_int|value_int|
+------+---------+
|     1|     null|
|     2|     null|
|  null|     null|
+------+---------+
Attempts:
2 left
💡 Hint
Casting null strings to int results in null values in Spark DataFrame.
❓ data_output
intermediate
1:30remaining
Count of nulls after type casting in Spark DataFrame
Given the DataFrame below, what is the count of null values in the 'age_int' column after casting 'age' from string to integer?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, isnan, when, count

spark = SparkSession.builder.getOrCreate()
data = [("25",), ("30",), (None,), ("",), ("40",)]
df = spark.createDataFrame(data, ["age"])
df_cast = df.select(col("age").cast("int").alias("age_int"))
null_count = df_cast.filter(col("age_int").isNull()).count()
print(null_count)
A1
B2
C3
D0
Attempts:
2 left
💡 Hint
Empty string and None cast to null integer.
🔧 Debug
advanced
2:00remaining
Identify the error in type casting with null handling
What error will this Spark code raise?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col

spark = SparkSession.builder.getOrCreate()
data = [("100",), ("abc",), (None,)]
df = spark.createDataFrame(data, ["score"])
df_cast = df.select(col("score").cast("int").alias("score_int"))
df_cast.show()
AValueError: invalid literal for int() with base 10: 'abc'
BRuntimeError: Null values not allowed in cast
CTypeError: Cannot cast string to int
D
+---------+
|score_int|
+---------+
|      100|
|     null|
|     null|
+---------+
Attempts:
2 left
💡 Hint
Invalid strings become null after casting in Spark, no error is raised.
🚀 Application
advanced
2:30remaining
Handling nulls after type casting for aggregation
You have a Spark DataFrame with a string column 'price' containing numeric strings and nulls. You want to compute the average price as a float. Which code snippet correctly handles nulls after casting?
Adf.selectExpr('avg(cast(price as float)) as avg_price').na.drop().show()
Bdf.selectExpr('avg(price) as avg_price').show()
Cdf.selectExpr('avg(cast(price as float)) as avg_price').show()
Ddf.selectExpr('avg(cast(price as int)) as avg_price').na.fill(0).show()
Attempts:
2 left
💡 Hint
Aggregation functions in Spark ignore nulls automatically.
🧠 Conceptual
expert
1:30remaining
Effect of type casting on null handling in Spark SQL expressions
In Spark SQL, what happens when you cast a string column containing empty strings and nulls to integer? Choose the most accurate statement.
AEmpty strings and nulls both become null integers without error.
BEmpty strings cause a runtime error, nulls become zero.
CEmpty strings become zero, nulls cause a runtime error.
DEmpty strings and nulls both become zero integers silently.
Attempts:
2 left
💡 Hint
Spark treats empty strings as nulls during cast to numeric types.

Practice

(1/5)
1. What does the cast() function do in Apache Spark DataFrames?
easy
A. It sorts the DataFrame by a column.
B. It removes null values from a DataFrame.
C. It filters rows based on a condition.
D. It changes the data type of a column to another specified type.

Solution

  1. Step 1: Understand the purpose of cast()

    The 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.
  2. Step 2: Compare with other options

    Other options describe different functions: removing nulls, filtering, or sorting, which are not related to type casting.
  3. Final Answer:

    It changes the data type of a column to another specified type. -> Option D
  4. Quick Check:

    cast() changes type = A [OK]
Hint: Remember: cast() changes column types, not data values [OK]
Common Mistakes:
  • Confusing cast() with filtering or sorting functions
  • Thinking cast() removes null values
  • Assuming cast() modifies data content instead of type
2. Which of the following is the correct syntax to cast a column named age to integer type in Spark DataFrame?
easy
A. df.select(df.age.convert('int'))
B. df.select(df.age.cast('int'))
C. df.select(df.age.toInt())
D. df.select(cast(df.age, 'int'))

Solution

  1. Step 1: Recall the correct cast syntax in Spark

    In Spark, to cast a column, you use column.cast('type'). So df.age.cast('int') is correct.
  2. 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 method toInt() which does not exist in Spark DataFrame columns. df.select(df.age.convert('int')) uses convert() which is not a Spark method.
  3. Final Answer:

    df.select(df.age.cast('int')) -> Option B
  4. Quick Check:

    Use column.cast('type') syntax = D [OK]
Hint: Use column.cast('type') to cast columns [OK]
Common Mistakes:
  • Using Python native methods like toInt() on Spark columns
  • Trying to use cast as a standalone function
  • Using non-existent methods like convert()
3. Given the following Spark code:
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?
medium
A. +-------+ |age_int| +-------+ | 25| | 30| | null| +-------+
B. +-------+ |age_int| +-------+ | 25| | 30| | 0| +-------+
C. RuntimeError due to casting None to int
D. SyntaxError in code

Solution

  1. 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.
  2. Step 2: Check the output of show()

    The DataFrame will display 25 and 30 as integers, and null for the None entry.
  3. Final Answer:

    +-------+ |age_int| +-------+ | 25| | 30| | null| +-------+ -> Option A
  4. Quick Check:

    Nulls remain null after cast = B [OK]
Hint: Casting None keeps null, does not convert to zero [OK]
Common Mistakes:
  • Expecting None to become 0 after cast
  • Thinking casting None causes error
  • Confusing syntax errors with runtime behavior
4. Identify the error in this Spark code snippet that tries to replace nulls in column salary with 0:
df = df.withColumn("salary", df["salary"].cast("int").fillna(0))
medium
A. withColumn() requires a function, not a column.
B. cast() cannot convert salary to int.
C. fillna() cannot be called on a Column object; it should be called on DataFrame.
D. The syntax is correct; no error.

Solution

  1. Step 1: Understand method chaining on Column vs DataFrame

    In Spark, fillna() is a DataFrame method, not a Column method. Calling fillna() on a Column object causes an error.
  2. Step 2: Correct usage

    To replace nulls after casting, use df = df.withColumn('salary', df['salary'].cast('int')) then df = df.fillna({'salary': 0}).
  3. Final Answer:

    fillna() cannot be called on a Column object; it should be called on DataFrame. -> Option C
  4. Quick Check:

    fillna() on DataFrame, not Column = C [OK]
Hint: Remember: fillna() is for DataFrame, not Column [OK]
Common Mistakes:
  • Calling fillna() on a Column instead of DataFrame
  • Assuming cast() changes null values automatically
  • Misusing withColumn() syntax
5. You have a DataFrame with a string column 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?
hard
A. df.withColumn('score_int', when(col('score').isNull(), -1).otherwise(col('score').cast('int')))
B. df.withColumn('score_int', col('score').cast('int').fillna(-1))
C. df.withColumn('score_int', col('score').cast('int').fillna({'score_int': -1}))
D. df.withColumn('score_int', col('score').cast('int').na.fill(-1))

Solution

  1. 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, use when() to check nulls before casting.
  2. Step 2: Analyze options

    df.withColumn('score_int', when(col('score').isNull(), -1).otherwise(col('score').cast('int'))) uses when() 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.
  3. Final Answer:

    df.withColumn('score_int', when(col('score').isNull(), -1).otherwise(col('score').cast('int'))) -> Option A
  4. Quick Check:

    Use when() for conditional null replacement before cast = A [OK]
Hint: Use when() to replace nulls before casting [OK]
Common Mistakes:
  • Using fillna() on columns instead of DataFrame
  • Expecting fillna() to replace nulls after cast automatically
  • Not handling nulls before casting
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