Skip to main content
NULL values (often represented as NA or null) are common in datasets and need to be handled appropriately during data processing. Spark provides several functions to handle null values in DataFrames.

1. Common Functions for Handling Null Values

  • dropna(): Drops rows or columns with null values.
  • fillna(): Fills null values with a specified value.
  • isnull(): Checks if a column contains null values.
  • coalesce(): Returns the first non-null value in a list of columns.
  • na.drop(): Alias for dropna().
  • na.fill(): Alias for fillna().

2. Examples

Example 1: Dropping Rows with Null Values

PySpark:
Spark SQL:
Output:

Example 2: Filling Null Values

PySpark:
Spark SQL:
Output:

Example 3: Checking for Null Values

PySpark:
Spark SQL:
Output:

Example 4: Using coalesce() to Handle Nulls

PySpark:
Spark SQL:
Output:

Example 5: Dropping Columns with Null Values

PySpark:
Spark SQL:
Output:

Example 6: Filling Nulls with Column-Specific Values

PySpark:
Spark SQL:
Output:

Example 7: Dropping Rows with Nulls in Specific Columns

PySpark:
Spark SQL:
Output:

3. Common Use Cases

  • Cleaning datasets by removing or filling null values.
  • Preparing data for machine learning by handling missing values.
  • Ensuring data quality by identifying and addressing null values.

4. Performance Considerations

  • Use dropna() judiciously, as it can reduce the size of the DataFrame.
  • Use fillna() with caution, as filling nulls with arbitrary values can introduce bias.
  • Use coalesce() for efficient handling of nulls in expressions.

5. Key Takeaways

  1. NULL values are common in datasets and need to be handled appropriately.
  2. Spark provides functions like dropna(), fillna(), and coalesce() to handle nulls.
  3. Handling nulls is generally efficient, but operations like dropna() can reduce the size of the DataFrame.
  4. In Spark SQL, similar functionality can be achieved using IS NULL, COALESCE, and CASE statements.