Null Handling and Data Cleaning — Practice Questions
1 free PYSPARK challenge on Null Handling and Data Cleaning, auto-graded in the browser. Each states the problem, shows the input and expected output, and explains the answer.
- Clean Order Prices by Handling Nulls and Filtering Negatives — Medium · PYSPARK · +100 XP
How to handle nulls and clean data
A null means a value is unknown, not that it is zero or empty. That one idea explains most null-related bugs. Because a null is unknown, comparing anything to it gives an unknown result, so the condition age = null matches nothing at all and age != 30 quietly excludes every row where age is null. To test for missing values, use isNull and isNotNull in PySpark, or IS NULL in SQL.
Arithmetic and string operations also propagate nulls: 5 plus null is null, and concatenating a null with concat gives null. Aggregates behave differently, because sum and avg skip nulls entirely. Know the difference before choosing a fix, since replacing nulls with zero changes every average you calculate afterwards. Joins have the same trap, because null keys never match each other.
You have three broad options, and the right one depends on what the missing value means. Drop the row with dropna when a record is useless without that field, such as an event with no user ID, and use the subset argument so that an unimportant missing column does not remove good data. Fill the value with fillna or coalesce when a sensible default exists, such as zero for a missing discount. Coalesce is the more flexible tool, because it returns the first non-null value from a list of columns, so you can fall back from a preferred source to a secondary one. The third option is to keep the null and report on it, which is often right when the absence itself carries meaning.
Real cleaning goes beyond nulls. Empty strings and placeholders such as NA, none or a blank space are not nulls to Spark, so convert them with a when expression or nullif before filling anything. Trim whitespace, standardise case, and cast text columns to real dates and numbers. What an invalid cast does depends on ANSI mode. With ANSI mode off, the default in Spark 3.x and the setting the example below ran with, it returns null instead of raising an error. With ANSI mode on, the default from Spark 4.0 and in Databricks SQL, it raises an error, and try_cast returns null instead. Either way, count the nulls before and after a cast to catch values that failed. Decide what to do with bad rows deliberately, and consider writing them to a separate table for inspection instead of dropping them, so you can measure how much data your rules reject and notice when a source starts to degrade.
Worked example
from pyspark.sql import functions as F
rows = [(1, " Asha ", "120"), (2, "NA", None), (3, "Ravi", "abc")]
df = spark.createDataFrame(rows, ["id", "name", "amount"])
clean = (df.withColumn("name", F.nullif(F.trim("name"), F.lit("NA")))
.withColumn("amount", F.col("amount").cast("int")))
clean.withColumn("amount", F.coalesce("amount", F.lit(0))).orderBy("id").show()
print("failed or missing amounts:", clean.filter(F.col("amount").isNull()).count())
Output
+---+----+------+
| id|name|amount|
+---+----+------+
| 1|Asha| 120|
| 2|NULL| 0|
| 3|Ravi| 0|
+---+----+------+
failed or missing amounts: 2
Preparing for an interview? PySpark coding interview questions · online PySpark compiler.