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:
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()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?
orders.filter(F.col("order_id").isNull() | F.col("quantity").isNull()).show()+--------+-----------+----------+--------+----------+---------+-------------------+
|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.
| mode | Bad row becomes | Use when |
|---|---|---|
| PERMISSIVE (default) | NULLs in bad fields | You want to inspect or quarantine bad rows |
| DROPMALFORMED | Dropped silently | Rarely: you lose data without knowing |
| FAILFAST | The whole read fails | Strict sources where any bad row is a bug |
Select, filter, sort
(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))+--------+---------+--------+
|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 rowsColumns 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
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)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| Method | Does |
|---|---|
| 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_format | Dates |
| F.trim, F.upper, F.regexp_replace | Text |
| 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:
events = spark.read.json("data/events/")
events.printSchema()
events.select("event_id", "type", "device.os", F.size("items").alias("n_items")).show(4)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 rowsdevice.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
(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")61 date folders, e.g. ['order_date=2026-10-01', 'order_date=2026-10-02']
168 orders on Diwali dayout/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 mode | If the folder exists |
|---|---|
| overwrite | Replace it |
| append | Add new files |
| error / errorifexists (default) | Fail |
| ignore | Do 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
Q2How do you handle corrupt records?1–3 yrs
Q3repartition vs partitionBy?1–3 yrs
Q4Why does writing produce many small files, and how do you fix it?3+ yrs
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. In PERMISSIVE mode, the row with quantity 'two' became...
2. Which adds or replaces a column?
3. How do you combine conditions in filter?
4. partitionBy('order_date') wrote how many folders for our 2 months?