Why PySpark?
ShopKart's order files are small today. But a shop with millions of customers creates gigabytes a day, and pandas on one laptop runs out of memory. Spark solves this by splitting data into partitions and processing them in parallel.
Your PySpark code
DataFrame operations in Python
Driver
Builds and optimizes a plan (Catalyst)
Executors
Run tasks, one per partition, in parallel
Result
Shown, collected, or written to files
Every example in this course ran on PySpark 4.0.1 on a laptop, with ShopKart's real order files. The outputs are exactly what we got.
Install and start Spark
$java -version # Spark needs Java 17 or 21$python3.11 -m venv venv && source venv/bin/activate$pip install pyspark==4.0.1 pandas pyarrow$export PYSPARK_PYTHON=$(which python) # workers must use the same Python
from pyspark.sql import SparkSession
spark = (SparkSession.builder
.appName("shopkart")
.master("local[*]") # use every CPU core of this laptop
.config("spark.ui.showConsoleProgress", "false") # no progress bars in the output
.getOrCreate())
spark.sparkContext.setLogLevel("ERROR")
print("Spark", spark.version)Spark 4.0.1SparkSession is your entry point: every DataFrame comes from it. On Databricks it already exists as spark.
Your first DataFrame
Two months of ShopKart order files (one CSV per day) sit in data/orders/. Spark reads the whole folder at once:
orders = spark.read.csv("data/orders/", header=True, inferSchema=True)
print(orders.count(), "orders in", orders.rdd.getNumPartitions(), "partitions")
orders.show(3)5316 orders in 8 partitions
+--------+-----------+----------+--------+----------+---------+-------------------+
|order_id|customer_id|product_id|quantity|unit_price| status| order_ts|
+--------+-----------+----------+--------+----------+---------+-------------------+
| 101734| 166| 11| 1| 1899|DELIVERED|2026-10-21 19:04:58|
| 101735| 130| 8| 1| 3499|DELIVERED|2026-10-21 12:36:45|
| 101736| 90| 9| 1| 799|DELIVERED|2026-10-21 17:37:37|
+--------+-----------+----------+--------+----------+---------+-------------------+
only showing top 3 rows5,316 rows, split into 8 partitions (pieces Spark processes in parallel, one per core here). A DataFrame is a table with named, typed columns, spread across those partitions.
Lazy evaluation: transformations vs actions
from pyspark.sql import functions as F
delivered = orders.filter(F.col("status") == "DELIVERED") # transformation: nothing runs yet
print(type(delivered).__name__)
print(delivered.count()) # action: now Spark runs a jobDataFrame
4146| Transformations (lazy: build the plan) | Actions (run the plan) |
|---|---|
| select, filter/where, withColumn, groupBy, join, orderBy, distinct | show, count, collect, take, first, toPandas |
| Return a new DataFrame instantly | write.parquet / csv / saveAsTable |
filter returned a DataFrame immediately without reading anything. Only count() made Spark read the files. Waiting lets Spark optimize the whole chain at once, for example reading only the columns you use.
delivered.select("order_id", "status").explain()== Physical Plan ==
*(1) Filter (isnotnull(status#22) AND (status#22 = DELIVERED))
+- FileScan csv [order_id#17,status#22] Batched: false, DataFilters: [isnotnull(status#22), (status#22 = DELIVERED)], Format: CSV, Location: InMemoryFileIndex(1 paths)[file:/private/tmp/claude-501/-Users-sudiptabiswas-claude/f6c71fe0-f8b1..., PartitionFilters: [], PushedFilters: [IsNotNull(status), EqualTo(status,DELIVERED)], ReadSchema: struct<order_id:string,status:string>explain() shows the physical plan: the filter is pushed into the file scan (DataFilters) and only two columns are read. You'll use this to debug slow jobs.
A real Spark 4 gotcha: inferSchema
Let's find orders with 2 or more items:
try:
orders.filter(F.col("quantity") >= 2).count()
except Exception as e:
print(type(e).__name__, "->", str(e).splitlines()[0][:150])
print(dict(orders.dtypes)["quantity"]) # inferSchema guessed: string!NumberFormatException -> [CAST_INVALID_INPUT] The value 'two' of the type "STRING" cannot be cast to "BIGINT" because it is malformed. Correct the value as per the syntax, or
stringOne file has a broken row where the supplier wrote two instead of 2. inferSchema saw it and decided the whole quantity column is text. Spark 4 turns on ANSI mode by default, so instead of silently returning wrong results it refuses to compare 'two' with a number. Lesson 2 fixes this properly with an explicit schema.
Spark and pandas
import pandas as pd
small = orders.limit(5).toPandas() # Spark -> pandas (only for small results!)
print(type(small).__name__, small.shape)DataFrame (5, 7)toPandas() pulls data to the driver as a pandas DataFrame: perfect for a small result to plot, dangerous on big data (it all has to fit in one machine's memory).
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is PySpark?Fresher
Q2Transformations vs actions?Fresher
Q3Why avoid inferSchema in production?1–3 yrs
Q4What is a partition?1–3 yrs
Q5What changed with ANSI mode in Spark 4?3+ yrs
Key takeaways
- PySpark lets the same Python code scale from a laptop to a cluster.
- Lazy plans plus explain() are how you understand what Spark does.
- Explicit schemas beat inferSchema: we saw why.
- Keep toPandas() for small results.
Frequently asked questions
What is PySpark?
PySpark is the Python API for Apache Spark, an engine that processes big data by splitting it across many CPU cores or machines. You write Python; Spark plans the work and runs it in parallel.
Do I need a cluster to learn PySpark?
No. pip install pyspark and run it in local mode on your laptop, as this course does. The same code runs unchanged on Databricks, AWS EMR, Azure Synapse or Fabric, just with more machines.
PySpark or pandas?
pandas runs on one machine and must fit the data in memory: great up to a few GB. PySpark spreads work across cores and machines and handles terabytes. Many pipelines use PySpark for the heavy lifting and pandas for small final results.
What do I need installed?
Python (3.10–3.12 is safest) and Java 17 or 21 (Spark runs on the JVM). Then pip install pyspark. Make sure workers use the same Python as your script by setting PYSPARK_PYTHON.
Is this the same as the PySpark in your Databricks course?
Same library, deeper. The Databricks course shows PySpark inside Databricks; this course teaches PySpark on its own, from installing it to window functions and UDFs, so it works anywhere.
🧠 Quick check: PySpark basics
1. What does spark.read.csv(...).filter(...) do before you call an action?
2. Which is an action?
3. Why did quantity >= 2 fail in our run?
4. What does local[*] mean?