Type casting changes data from one type to another. Null handling manages missing or empty data safely.
When you want to convert a column from string to number to do math.
When you need to replace missing values to avoid errors in calculations.
When reading data from files that may have empty or null fields.
When preparing data for machine learning models that require specific types.
When cleaning data to ensure consistent types across columns.
Syntax
Apache Spark
from pyspark.sql.functions import col
df = df.withColumn('new_column', col('old_column').cast('new_type'))
# To handle nulls, use functions like fillna or when
df = df.fillna({'column_name': default_value})
Use cast() to convert column types.
Use fillna() to replace nulls with default values.
Cast 'age' to int and replace nulls with 0 in one step.
Apache Spark
from pyspark.sql.functions import when
df = df.withColumn('age_clean', when(col('age').isNull(), 0).otherwise(col('age').cast('int')))
Sample Program
This program creates a DataFrame with ages as strings, some nulls and 'NaN' strings. It replaces 'NaN' with null, then casts the age to integer and replaces nulls with 0.
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, when
spark = SparkSession.builder.appName('TypeCastingNullHandling').getOrCreate()
# Sample data with string ages and some nulls
data = [
('Alice', '23'),
('Bob', None),
('Charlie', '35'),
('David', 'NaN'),
('Eve', None)
]
columns = ['name', 'age']
df = spark.createDataFrame(data, columns)
# Show original dataprint('Original Data:')
df.show()
# Replace 'NaN' string with nullfrom pyspark.sql.functions import when
df = df.withColumn('age', when(col('age') == 'NaN', None).otherwise(col('age')))
# Cast age to integer and replace nulls with 0
df = df.withColumn('age_int', when(col('age').isNull(), 0).otherwise(col('age').cast('int')))
print('After type casting and null handling:')
df.show()
spark.stop()
OutputSuccess
Important Notes
Null values can cause errors if not handled before calculations.
Always check data types before casting to avoid unexpected errors.
Use when for flexible null handling and conditional logic.
Summary
Type casting changes data types to fit your analysis needs.
Null handling replaces or manages missing data safely.
Use Spark functions like cast(), fillna(), and when() for these tasks.
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
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.
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 D
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
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.
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.
Final Answer:
df.select(df.age.cast('int')) -> Option B
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()
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
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.
Step 2: Correct usage
To replace nulls after casting, use df = df.withColumn('salary', df['salary'].cast('int')) then df = df.fillna({'salary': 0}).
Final Answer:
fillna() cannot be called on a Column object; it should be called on DataFrame. -> Option C
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
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.
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.
Final Answer:
df.withColumn('score_int', when(col('score').isNull(), -1).otherwise(col('score').cast('int'))) -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.