Skip to content
TeachTrails
Data EngineeringPySpark

PySpark DataFrames: Read CSV and JSON, Schemas, Clean and Write Parquet

Read CSV and JSON with PySpark, define schemas, handle bad rows, select, filter, withColumn, nulls, nested JSON and writing partitioned Parquet, all run on Spark 4.

Sukanya Saha, Technology Consultant

13 min read

Beginner friendly

Read with a schema (fixing lesson 1)

We start the session as in lesson 1 (same spark and F). This time we tell Spark exactly what each column is:

PySpark · Python
from pyspark.sql.types import StructType, StructField, IntegerType, StringType, DecimalType, TimestampType

orders_schema = StructType([
    StructField("order_id", IntegerType()),
    StructField("customer_id", IntegerType()),
    StructField("product_id", IntegerType()),
    StructField("quantity", IntegerType()),
    StructField("unit_price", DecimalType(10, 2)),
    StructField("status", StringType()),
    StructField("order_ts", TimestampType()),
])
orders = (spark.read
          .option("header", True)
          .option("mode", "PERMISSIVE")                     # keep bad rows, put NULLs in bad fields
          .schema(orders_schema)
          .csv("data/orders/"))
orders.printSchema()
Output
root
 |-- order_id: integer (nullable = true)
 |-- customer_id: integer (nullable = true)
 |-- product_id: integer (nullable = true)
 |-- quantity: integer (nullable = true)
 |-- unit_price: decimal(10,2) (nullable = true)
 |-- status: string (nullable = true)
 |-- order_ts: timestamp (nullable = true)

Now quantity is an integer. What happened to the broken row?

PySpark · Python
orders.filter(F.col("order_id").isNull() | F.col("quantity").isNull()).show()
Output
+--------+-----------+----------+--------+----------+---------+-------------------+
|order_id|customer_id|product_id|quantity|unit_price|   status|           order_ts|
+--------+-----------+----------+--------+----------+---------+-------------------+
|    NULL|         17|         3|    NULL|   4999.00|DELIVERED|2026-11-30 10:15:00|
+--------+-----------+----------+--------+----------+---------+-------------------+

PERMISSIVE mode kept the row but set the fields it couldn't parse (100999x, two) to NULL. Nothing crashed, and the bad row is easy to find.

modeBad row becomesUse when
PERMISSIVE (default)NULLs in bad fieldsYou want to inspect or quarantine bad rows
DROPMALFORMEDDropped silentlyRarely: you lose data without knowing
FAILFASTThe whole read failsStrict sources where any bad row is a bug

Select, filter, sort

PySpark · Python
(orders
   .select("order_id", "status", (F.col("quantity") * F.col("unit_price")).alias("amount"))
   .filter((F.col("status") == "DELIVERED") & (F.col("amount") > 4000))
   .orderBy(F.desc("amount"))
   .show(5))
Output
+--------+---------+--------+
|order_id|   status|  amount|
+--------+---------+--------+
|  104734|DELIVERED|14997.00|
|  102818|DELIVERED|14997.00|
|  103578|DELIVERED|14997.00|
|  103721|DELIVERED|14997.00|
|  104559|DELIVERED|14997.00|
+--------+---------+--------+
only showing top 5 rows

Columns are expressions: F.col("quantity") * F.col("unit_price") builds a new column, and .alias() names it. Combine conditions with & (and), | (or), ~ (not), with each condition in brackets. Python's and/or don't work on columns.

Clean: nulls, new columns, renames

PySpark · Python
clean = (orders
    .dropna(subset=["order_id", "quantity"])                      # drop the broken row
    .withColumn("amount", F.col("quantity") * F.col("unit_price"))
    .withColumn("order_date", F.to_date("order_ts"))
    .withColumn("is_big", F.when(F.col("amount") >= 5000, True).otherwise(False))
    .withColumnRenamed("status", "order_status"))
print(clean.count())
clean.select("order_id", "amount", "order_date", "is_big", "order_status").show(3)
Output
5315
+--------+-------+----------+------+------------+
|order_id| amount|order_date|is_big|order_status|
+--------+-------+----------+------+------------+
|  101734|1899.00|2026-10-21| false|   DELIVERED|
|  101735|3499.00|2026-10-21| false|   DELIVERED|
|  101736| 799.00|2026-10-21| false|   DELIVERED|
+--------+-------+----------+------+------------+
only showing top 3 rows
MethodDoes
dropna(subset=[...]) / fillna({...})Remove or fill nulls
withColumn(name, expr)Add or replace a column
F.when(cond, a).otherwise(b)If/else (like SQL CASE WHEN)
withColumnRenamed(old, new)Rename
F.to_date, F.year, F.date_formatDates
F.trim, F.upper, F.regexp_replaceText
dropDuplicates([cols])Remove duplicates (lesson 4 shows a better way)

Nested JSON

The app's events are JSON lines with nested objects and arrays. Spark infers nested types:

PySpark · Python
events = spark.read.json("data/events/")
events.printSchema()
events.select("event_id", "type", "device.os", F.size("items").alias("n_items")).show(4)
Output
root
 |-- coupon: string (nullable = true)
 |-- customer_id: long (nullable = true)
 |-- device: struct (nullable = true)
 |    |-- app_version: string (nullable = true)
 |    |-- os: string (nullable = true)
 |-- event_id: long (nullable = true)
 |-- items: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- product_id: long (nullable = true)
 |    |    |-- qty: long (nullable = true)
 |-- query: string (nullable = true)
 |-- ts: string (nullable = true)
 |-- type: string (nullable = true)

+--------+--------+-------+-------+
|event_id|    type|     os|n_items|
+--------+--------+-------+-------+
|     161|checkout|    web|      2|
|     162|checkout|android|      1|
|     163|  search|android|   NULL|
|     164|app_open|    web|   NULL|
+--------+--------+-------+-------+
only showing top 4 rows

device.os reaches into a struct; F.size("items") counts an array (NULL when there's no array). To get one row per item you'd use F.explode("items").

Write partitioned Parquet

PySpark · Python
(clean.write
   .mode("overwrite")
   .partitionBy("order_date")
   .parquet("out/orders_clean"))

import os
folders = sorted(d for d in os.listdir("out/orders_clean") if d.startswith("order_date="))
print(len(folders), "date folders, e.g.", folders[:2])
print(spark.read.parquet("out/orders_clean").filter("order_date = '2026-10-20'").count(), "orders on Diwali day")
Output
61 date folders, e.g. ['order_date=2026-10-01', 'order_date=2026-10-02']
168 orders on Diwali day
🗂️ out/orders_clean/
out/orders_clean/
├── order_date=2026-10-01/part-0000...snappy.parquet
├── order_date=2026-10-02/part-0000...snappy.parquet
├── ...                      (61 folders, one per day)
└── _SUCCESS

Reading back with order_date = '2026-10-20' only opens that one folder (partition pruning). 168 orders that day, the first day of ShopKart's Diwali sale.

Write modeIf the folder exists
overwriteReplace it
appendAdd new files
error / errorifexists (default)Fail
ignoreDo nothing

🎯 Interview questions on this topic

Try to answer out loud first, then tap to check.

Q1How do you read a CSV with a header and a schema in PySpark?Fresher
spark.read.option('header', True).schema(schema).csv(path), where schema is a StructType or a DDL string. Add mode (PERMISSIVE/FAILFAST) to control bad rows.
Q2How do you handle corrupt records?1–3 yrs
Use PERMISSIVE with columnNameOfCorruptRecord to keep the raw text of bad rows in a column, split good and bad rows, write bad ones to a quarantine location and alert. FAILFAST for strict sources.
Q3repartition vs partitionBy?1–3 yrs
repartition(n or cols) changes how data is split in memory (a shuffle) before processing or writing. partitionBy(col) on the writer controls the folder layout on disk. They're often used together: repartition by the partition column first to avoid many small files.
Q4Why does writing produce many small files, and how do you fix it?3+ yrs
Each task writes at least one file per output partition, so many tasks × many partition values = many files. Fix with repartition/coalesce before writing, repartition by the partitionBy column, maxRecordsPerFile, or a table format with compaction (Delta OPTIMIZE).

Key takeaways

  • An explicit schema turned lesson 1's crash into one visible bad row.
  • Clean with column expressions; combine conditions with & and |.
  • Parquet partitioned by date makes later reads fast.
  • Never partition by IDs.

Frequently asked questions

How do I give a DataFrame a schema?

Build a StructType of StructFields (name, type) or use a DDL string like 'order_id INT, status STRING', and pass it with spark.read.schema(...). It's faster than inferSchema and protects you from surprise types.

What happens to bad rows when reading CSV?

It depends on mode: PERMISSIVE (default) keeps the row and sets bad fields to NULL, DROPMALFORMED drops it, FAILFAST stops with an error. You can also capture the raw text with columnNameOfCorruptRecord.

Why write Parquet instead of CSV?

Parquet is columnar, compressed and keeps types, so files are smaller and queries read only the columns they need. CSV has no types and must be parsed every time.

What does partitionBy do when writing?

It writes one folder per value (order_date=2026-10-20/). Queries that filter on that column read only matching folders. Choose low-cardinality columns like dates, never IDs.

🧠 Quick check: reading and writing

  1. 1. In PERMISSIVE mode, the row with quantity 'two' became...

  2. 2. Which adds or replaces a column?

  3. 3. How do you combine conditions in filter?

  4. 4. partitionBy('order_date') wrote how many folders for our 2 months?

PySpark for Beginners

Part 2 of 5: PySpark DataFrames