Databricks PySpark
PySpark is the Python interface to Apache Spark. It lets you process datasets that are too large for a single computer using familiar Python commands. Databricks notebooks include Spark by default, so you can start writing PySpark code the moment a notebook connects to compute.
The DataFrame: Your Main Tool
A DataFrame is a table of rows and named columns. It looks like a spreadsheet, but Spark splits it into pieces and spreads those pieces across many machines. Each machine works on its own piece at the same time, which makes large jobs finish quickly.
ONE DATAFRAME, MANY MACHINES
──────────────────────────────────────────────────────────
DataFrame: orders (1 billion rows)
Partition 1 Partition 2 Partition 3
rows 1–300M rows 300M–600M rows 600M–1B
│ │ │
Machine A Machine B Machine C
└───────────────────┴──────────────────┘
▼
Combined result
Reading Data
The spark.read tool loads files and tables into DataFrames. Choose the method that matches your source.
# CSV file
orders = spark.read.csv("/Volumes/main/shop/files/orders.csv",
header=True, inferSchema=True)
# JSON file
events = spark.read.json("/Volumes/main/shop/files/events.json")
# Existing table
customers = spark.table("main.shop.customers")
The header option tells Spark that the first row holds column names. The inferSchema option makes Spark guess the data type of each column.
Looking at Your Data
orders.printSchema() # column names and types display(orders) # interactive grid in Databricks orders.count() # number of rows orders.show(5) # first five rows as plain text
Core Transformations
Select Columns
from pyspark.sql.functions import col
small = orders.select("order_id", "city", "amount")
Filter Rows
big_orders = orders.filter(col("amount") > 500)
Create or Change a Column
from pyspark.sql.functions import round
with_tax = orders.withColumn("amount_with_tax", round(col("amount") * 1.18, 2))
Group and Summarize
from pyspark.sql.functions import sum, avg, count
city_report = (orders
.groupBy("city")
.agg(sum("amount").alias("total_sales"),
avg("amount").alias("average_order"),
count("order_id").alias("order_count")))
Join Two DataFrames
joined = orders.join(customers, on="customer_id", how="inner")
Sort the Result
top_cities = city_report.orderBy(col("total_sales").desc())
Lazy Evaluation: The Recipe Idea
Spark does not run a transformation the moment you type it. Spark records each step in a plan, much like a cook who writes a recipe before turning on the stove. The cooking starts only when you ask for a result. Commands that start the work are called actions.
TRANSFORMATIONS (build the plan) ACTIONS (run the plan)
────────────────────────────────── ───────────────────────────
select, filter, withColumn, count, show, display,
groupBy, join, orderBy collect, write, saveAsTable
orders ─► filter ─► withColumn ─► groupBy ─► [ACTION: display]
│
Spark optimizes the whole plan
and runs it once
Lazy evaluation gives Spark room to improve your work. Spark can reorder steps, skip unused columns, and read less data before it spends any computing power.
Writing Results
city_report.write.mode("overwrite").saveAsTable("main.shop.city_report")
The overwrite mode replaces the table contents. The append mode adds rows to existing data. Delta format is the default table format in Databricks.
Example: Monthly Sales Report
A shop owner wants the total sales for each city, limited to orders above a minimum amount. The code below reads the orders, filters them, groups by city, and saves the report.
from pyspark.sql.functions import col, sum
report = (spark.table("main.shop.orders")
.filter(col("amount") >= 100)
.groupBy("city")
.agg(sum("amount").alias("total_sales"))
.orderBy(col("total_sales").desc()))
report.write.mode("overwrite").saveAsTable("main.shop.monthly_report")
display(report)
EXAMPLE FLOW
──────────────────────────────────────────────────────────
orders table ─► keep amount ≥ 100 ─► group by city ─► sum amount
│
sorted report ◄─────────────────┘
│
saved as a table
Habits That Keep Code Clean
- Chain transformations inside parentheses so each step sits on its own line.
- Select only the columns you need as early as possible.
- Avoid collect on large DataFrames, because it pulls every row onto one machine.
- Name columns clearly with alias.
PySpark Compared with Pandas
Pandas is a popular Python library that processes data on a single computer. PySpark spreads the same kind of work across a group of computers. Small files that fit in memory run well in Pandas. Datasets with millions or billions of rows belong in PySpark. Databricks lets you convert a small PySpark result into a Pandas DataFrame with the toPandas command, so you can use both tools in one notebook.
Using SQL Inside PySpark
Spark treats SQL and DataFrame code as equals. Both styles produce the same plan and the same speed. Analysts who know SQL can mix the two styles in a single notebook.
orders.createOrReplaceTempView("orders_view")
result = spark.sql("""
SELECT city, SUM(amount) AS total_sales
FROM orders_view
GROUP BY city
""")
display(result)
A temporary view lasts only for the current session. Save the result as a table when other people need it.
Handling Missing Values
Real data contains blanks. PySpark offers simple tools to find and fix them.
orders.dropna(subset=["amount"]) # remove rows with no amount
orders.fillna({"city": "Unknown"}) # replace blank cities
orders.filter(col("city").isNull()) # find rows with blank cities
Decide on a clear rule for each column before you clean it. Removing too many rows hides real patterns, and filling every blank with zero can distort averages.
Key Points
- PySpark runs Python code on Spark across many machines.
- A DataFrame is a distributed table with named columns.
- Transformations build a plan, and actions run it.
- The select, filter, withColumn, groupBy, and join commands cover most daily tasks.
- Lazy evaluation lets Spark improve the plan before it executes.
- Write results with saveAsTable to share them through SQL.
