PySpark DataFrames
Read, transform and write data with the PySpark DataFrame API: schemas, column expressions, aggregations, window functions and handling nested data.
Intermediate · about 12 hours · difficulty 3/5
Learn first: Spark Architecture and Execution Model, Window Functions
The PySpark DataFrame API is what you will write daily. If you know SQL and pandas, most of it will feel familiar; the difference is that it runs across a cluster.
Reading and writing
spark.read.parquet(path),.csvwith options,.json.- Define explicit schemas (
StructType) for CSV and JSON instead ofinferSchema, which is slow and can guess wrong. - Write with
.mode("overwrite")and.partitionBy("dt"). Use dynamic partition overwrite so a rerun replaces only the affected dates.
Transformations
select,withColumn,filter,drop,distinct,dropDuplicates.- Functions from
pyspark.sql.functions(col,when,to_date,from_utc_timestamp,regexp_replace). groupBy().agg(...)for aggregates.- Window functions via
Window.partitionBy().orderBy(), the same patterns you learned in SQL. - Nested data:
explodearrays, access struct fields with dot notation.
Spark SQL
Register a temp view and write plain SQL with spark.sql(...). DataFrame code and SQL compile to the same plan, so use whichever is clearer.
UDFs
Python UDFs are slow because rows move between the JVM and Python. Prefer built-in functions; if you must, use pandas UDFs (vectorised).
Testing
Write transformations as functions that take and return DataFrames, and test them with tiny DataFrames in pytest.
Pitfalls
- Using
inferSchemain production and getting a type change one day. - Overwrite mode wiping the whole table when you meant to replace one partition.
- Chaining hundreds of
withColumncalls in a loop, which bloats the plan.
You are ready to move on when you can rebuild your earlier pandas cleaning job in PySpark with an explicit schema, a window-based dedup and partitioned output, plus pytest tests.
Key concepts
- Reading and writing formats
- Explicit schemas with StructType
- Column expressions and functions
- groupBy and agg
- Window functions in PySpark
- explode and nested structs
- Spark SQL and temp views
- Dynamic partition overwrite
- pandas UDFs
- Testing PySpark code
Mini project
Using the NYC taxi dataset (used in the DE Zoomcamp) or a large Indian open dataset, build a PySpark job that cleans trips, deduplicates, computes daily metrics per zone with window functions, and writes partitioned Parquet. Include pytest tests for two transformations.
Check yourself
Why is a Python UDF that uppercases a string slower than F.upper(), and what happens to the data when the UDF runs?
Free resources
- PySpark documentation (Apache Spark)
- Spark SQL, DataFrames and Datasets guide (Apache Spark)
- Data Engineering Zoomcamp (DataTalksClub)