Time to write real code. We'll use ShopKart's first day of orders: a JSON file with one order per line, and a customers CSV. It has deliberate problems, just like real data: one order has no customer, and one has a quantity of -1.
{"order_id": "O1001", "customer_id": "C01", "product": "Headphones", "quantity": 1, "price": 1999.0, "status": "DELIVERED", "order_ts": "2026-11-18T10:15:00", "updated_at": "2026-11-18T10:15:00"}
{"order_id": "O1005", "customer_id": null, "product": "Charger", "quantity": 1, "price": 499.0, "status": "PLACED", "order_ts": "2026-11-18T16:05:00", "updated_at": "2026-11-18T16:05:00"}📄Read
JSON + CSV
🧹Clean
filter, withColumn
🔗Combine
groupBy, join, window
💾Save
A Delta table
Step 1: Read files
from pyspark.sql import functions as F
orders = spark.read.json("/Volumes/shopkart/raw/landing/orders/")
customers = (spark.read
.option("header", True) # first line has column names
.option("inferSchema", True) # guess types (fine for exploring)
.csv("/Volumes/shopkart/raw/landing/customers/"))
orders.printSchema()
display(orders)F is the standard nickname for pyspark.sql.functions: every built-in function lives there. Spark guessed the types from JSON, but timestamps came in as plain text. For real pipelines, declare the schema:
orders_schema = """
order_id STRING, customer_id STRING, product STRING,
quantity INT, price DOUBLE, status STRING,
order_ts TIMESTAMP, updated_at TIMESTAMP
"""
orders = spark.read.schema(orders_schema).json("/Volumes/shopkart/raw/landing/orders/")
orders.printSchema()Step 2: select and filter
delivered = (orders
.select("order_id", "customer_id", "product", "quantity", "price", "status")
.filter(F.col("status") == "DELIVERED"))
display(delivered)F.col("status") means “the status column”. Result: 3 delivered orders.
Step 3: Clean and add columns
orders_clean = (orders
.filter(F.col("customer_id").isNotNull()) # drop orders with no customer
.filter(F.col("quantity") > 0) # drop impossible quantities
.withColumn("amount", F.col("quantity") * F.col("price"))
.withColumn("order_date", F.to_date("order_ts")))
display(orders_clean)| order_id | customer_id | product | quantity | price | amount |
|---|---|---|---|---|---|
| O1001 | C01 | Headphones | 1 | 1999.0 | 1999.0 |
| O1002 | C02 | Phone Case | 2 | 299.0 | 598.0 |
| O1003 | C03 | Smartwatch | 1 | 4999.0 | 4999.0 |
| O1004 | C01 | Charger | 3 | 499.0 | 1497.0 |
The order with no customer and the one with quantity -1 are gone: 6 rows in, 4 rows out.
Step 4: groupBy and aggregate
revenue_by_product = (orders_clean
.groupBy("product")
.agg(F.sum("amount").alias("revenue"),
F.count("*").alias("orders"))
.orderBy(F.desc("revenue")))
display(revenue_by_product)| product | revenue | orders |
|---|---|---|
| Smartwatch | 4999.0 | 1 |
| Headphones | 1999.0 | 1 |
| Charger | 1497.0 | 1 |
| Phone Case | 598.0 | 1 |
Other common aggregates: F.avg, F.min, F.max, F.countDistinct, F.collect_list.
Step 5: Joins
orders_with_city = orders_clean.join(customers, on="customer_id", how="left")
display(orders_with_city.select("order_id", "name", "city", "amount"))| Join type | Keeps | Use it when |
|---|---|---|
| inner (default) | Only rows that match on both sides | You only want orders with a known customer |
| left | All left rows; right side or nulls | Keep every order even if the customer is missing |
| right / full | All right rows / all rows from both | Rare; reconciliation reports |
| left_semi | Left rows that HAVE a match (no right columns) | Customers who ordered something |
| left_anti | Left rows with NO match | Customers who never ordered; finding missing data |
Step 6: Window functions (interview favourite)
A window function calculates something over a group of rows without collapsing them, unlike groupBy. Classic use: “the latest record per key” or “the top order per customer”.
from pyspark.sql import Window
# For each customer, number their orders from biggest to smallest.
by_customer = Window.partitionBy("customer_id").orderBy(F.desc("amount"))
biggest_order = (orders_clean
.withColumn("rank", F.row_number().over(by_customer))
.filter(F.col("rank") == 1))
display(biggest_order.select("customer_id", "order_id", "amount"))| customer_id | order_id | amount |
|---|---|---|
| C01 | O1001 | 1999.0 |
| C02 | O1002 | 598.0 |
| C03 | O1003 | 4999.0 |
Asha (C01) has two orders; the 1,999 one ranks first. Other window functions: rank, dense_rank, lag/lead (previous/next row), and running totals with F.sum(...).over(window).
Step 7: The same in SQL
orders_clean.createOrReplaceTempView("orders_clean")
customers.createOrReplaceTempView("customers")
city_revenue = spark.sql("""
SELECT c.city, SUM(o.amount) AS revenue
FROM orders_clean o
JOIN customers c ON o.customer_id = c.customer_id
GROUP BY c.city
ORDER BY revenue DESC
""")
display(city_revenue)A temp view gives a DataFrame a name SQL can use, for this session only. Bengaluru comes first (4,999). In a Databricks notebook you could also write a %sql cell directly.
Step 8: Save as a table
(orders_clean.write
.mode("overwrite") # replace the table if it exists
.saveAsTable("shopkart.demo.orders")) # catalog.schema.table
display(spark.table("shopkart.demo.orders"))| Write mode | If the table exists |
|---|---|
| append | Add the new rows |
| overwrite | Replace all rows |
| error / errorifexists (default) | Fail |
| ignore | Do nothing |
On Databricks every table is a Delta table by default, named catalog.schema.table. That's where the next lesson begins.
PySpark cheat sheet
df.select("a", "b") # pick columns
df.filter(F.col("a") > 5) # keep rows (same as .where)
df.withColumn("c", F.col("a") * 2) # add / replace a column
df.withColumnRenamed("a", "x") # rename
df.drop("b") # remove a column
df.dropDuplicates(["id"]) # one row per id
df.fillna({"city": "Unknown"}) # replace nulls
df.groupBy("k").agg(F.sum("v").alias("t")) # aggregate
df.join(other, "id", "left") # join
df.orderBy(F.desc("t")) # sort
F.when(F.col("a") > 0, "pos").otherwise("neg") # if / else
F.to_date("ts"), F.year("ts"), F.date_format("ts", "yyyy-MM")
F.lower, F.upper, F.trim, F.concat_ws("-", "a", "b"), F.coalesce("a", "b")🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you remove duplicate rows in PySpark?Fresher+
Q2Difference between select and withColumn?Fresher+
Q3Find the second-highest order amount per customer.1–3 yrs+
Q4What are left_semi and left_anti joins?1–3 yrs+
Q5Why avoid Python UDFs, and what's the alternative?1–3 yrs+
Q6How do you handle a column that is sometimes a string and sometimes a number in JSON?3+ yrs+
Key takeaways
- ✓Read with a schema, clean with filter/withColumn, combine with groupBy/join/window, save with saveAsTable.
- ✓Window functions answer 'top N per group' and 'latest per key' questions.
- ✓PySpark and SQL are interchangeable; both are optimized by Catalyst.
- ✓Our first revenue report works. Next: making the table itself reliable with Delta Lake.
Frequently asked questions
What is a PySpark DataFrame?
A table spread across the cluster, with named columns and types (a schema). You describe what you want with methods like select, filter and groupBy, and Spark runs it in parallel.
Should I use PySpark or Spark SQL?
Both compile to the same plan and run at the same speed. Use whichever reads better: SQL for simple queries, PySpark for reusable logic, loops over columns and functions. Most teams mix them.
Why define a schema instead of inferSchema?
Inferring reads the data an extra time and can guess wrong (an ID like 007 becomes the number 7). A declared schema is faster, safer and documents what you expect.
What is the difference between row_number, rank and dense_rank?
For ties: row_number gives 1, 2, 3 (always unique); rank gives 1, 1, 3 (skips); dense_rank gives 1, 1, 2 (no gaps). row_number is the usual choice for de-duplication.
Why should I avoid Python UDFs?
A Python UDF sends every row from the JVM to Python and back, and Catalyst can't optimize inside it. Built-in functions in pyspark.sql.functions are much faster. If you must, use a pandas (vectorized) UDF.
🧠 Quick check: PySpark DataFrames
1. Which keeps only delivered orders?
2. How do you add an amount column?
3. You want the biggest order PER customer. Use...
4. A left join keeps...
Checking your access…