Find and quarantine malformed CSV rows in PySpark

Thomas Reid · 19 November 2026 · Free tutorial · PySpark 4.2.0

A successful CSV read doesn't prove every row is usable. Capture parsing failures, apply your own validation rules, and save rejected records with a reason so they can be investigated.

The snippets below use this local session. The complete downloadable scripts include setup, imports and result checks.

from pathlib import Path
from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.master("local[2]").appName("Recipe").getOrCreate()

When working interactively, call spark.stop() after the final example. Run the CSV recipe as a saved script so __file__ identifies its folder.

Separate parsing errors from invalid business values

The download contains data/sales.csv with five records. Two are valid. One has text where an amount should be, one has an empty amount, and one has a negative amount.

sale_id,amount
1,12.5
2,8.0
3,oops
4,
5,-2.0

The text oops can't be parsed as a double. An empty amount and a negative amount need separate business rules. We reject both here, but another pipeline might allow negative amounts for refunds. For production money calculations, choose an appropriate decimal type rather than copying this teaching example's double type.

Read with an explicit schema

folder = Path(__file__).resolve().parent
source = (folder / "data" / "sales.csv").as_uri()
parsed = (
    spark.read.option("header", True)
    .option("mode", "PERMISSIVE")
    .option("columnNameOfCorruptRecord", "_corrupt_record")
    .schema("sale_id INT, amount DOUBLE, _corrupt_record STRING")
    .csv(source)
    .cache()
)

The schema includes a string field called _corrupt_record, matching columnNameOfCorruptRecord. In permissive mode this preserves the raw text of a record identified as corrupt. Pass the schema itself to schema(); a quoted Python variable name isn't the schema object.

The script caches and materialises the parsed DataFrame before inspecting rejected rows. Spark restricts queries that read only the corrupt-record column directly from raw CSV or JSON. The example retains all parsed columns and releases the cache in a finally block.

Add a rejection reason

checked = parsed.withColumn(
    "rejection_reason",
    F.when(F.col("_corrupt_record").isNotNull(), "CSV parse error")
    .when(F.col("sale_id").isNull(), "Missing sale_id")
    .when(F.col("amount").isNull(), "Missing amount")
    .when(F.col("amount") < 0, "Negative amount"),
)
rejected = checked.filter(F.col("rejection_reason").isNotNull())
accepted = checked.filter(F.col("rejection_reason").isNull()).drop(
    "_corrupt_record", "rejection_reason"
)

The first matching condition supplies the reason. This makes parser errors distinguishable from missing required values and negative amounts. The accepted and rejected filters use complementary null checks, so every input record belongs to one output.

sale_id  amount  _corrupt_record  rejection_reason
3        NULL    3,oops           CSV parse error
4        NULL    NULL             Missing amount
5        -2.0    NULL             Negative amount

Write rejected rows somewhere useful

The complete script writes output/csv_check/accepted and output/csv_check/rejected as Parquet directories. Rejected output retains the parsed fields, corrupt input text when available, and the reason. It asserts two accepted records and three rejected records before writing.

Each run overwrites these example output directories. A production quarantine should preserve run history and source-file identity so you can fix and replay failures. Retain original input files too: _corrupt_record isn't a copy of every source line, and business-rule failures can have a null corrupt-record field.

Choose a parsing mode deliberately

PERMISSIVE lets you inspect problems, FAILFAST stops at a malformed record, and DROPMALFORMED discards records the parser considers malformed. None replaces your business validation. Missing or extra CSV tokens aren't a reliable universal corruption test; don't use the corrupt-record field as your only check.

Start with the schema tutorial if field types are unfamiliar. Compare this approach with dropping missing required values: retaining rejected rows makes failures easier to explain later.

Run the complete example

Download the free examples ZIP and extract it. The code was checked with Python 3.13, Java 21 and PySpark 4.2.0. Use the installation guide if you need Java or Python first. From the extracted folder, run these PowerShell commands:

py -3.13 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe malformed_csv.py

On Linux or macOS, create the environment with python3 -m venv .venv and use .venv/bin/python for the install and run commands. Each script starts a local Spark session, checks the results and stops the session when finished.

Read the complete code on GitHub. Reference: Apache Spark 4.2 documentation.

Related recipes