Sub topic 3
What a DataFrame is
This chapter assumes you can read basic Python or SQL, that you know what rows, columns and types are in a table, and that you can attach a notebook to compute in a Databricks workspace. It builds the working model of a Spark DataFrame. Later chapters cover reading files, transformations and joins in detail.
The working model
A DataFrame is a distributed table with named, typed columns. You describe what you want from it, and Spark decides how to run that work across the machines in your cluster.
Three properties matter most:
- Distributed. The rows are split into partitions. A partition is a chunk of rows that one task processes on one core. Your notebook code runs on the driver, the node that coordinates the work. The rows themselves live on the executors, the nodes that do the work.
- Schema-bound. Every column has a name and a data type, and Spark knows these before it processes a single row.
- Immutable. No DataFrame operation changes an existing DataFrame. Each operation returns a new DataFrame that describes a new result.
The third property explains a common early mistake. Calling df.filter(...) and ignoring the return value does nothing useful, because df is unchanged.
A DataFrame object in your notebook is not the data. It is a plan: a description of how to produce the data. Spark runs the plan only when you ask for a result. The chapter on lazy evaluation covers this in depth. For now, remember that holding a DataFrame variable costs almost nothing, and that creating one rarely does heavy work.
How a DataFrame relates to the session
In a Databricks notebook, a SparkSession named spark already exists. It is the entry point for creating DataFrames. Every DataFrame you build comes from spark, either by reading data (spark.read), by building rows in memory (spark.createDataFrame), or by running SQL (spark.sql). Transformations on a DataFrame then produce more DataFrames.
Creating a small DataFrame
The fastest way to get a DataFrame to experiment with is createDataFrame. This example builds one from in-memory rows, gives it a schema as a DDL-style string, and converts a string column into a real date.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
orders.printSchema()
display(orders)Walking through it:
spark.createDataFrametakes a list of tuples and a schema string. Each tuple is one row, and the schema names and types the positions in order.- The fourth row has
Noneforamount. In a DataFrame this becomes a SQLNULL. The column type isDOUBLE, and any column can hold nulls unless you say otherwise. withColumnreturns a new DataFrame. The assignmentorders = ...rebinds the Python name to that new DataFrame. The old one still exists until Python discards it.printSchema()prints the column names and types as a tree.display()is a Databricks function that renders the rows as an interactive table.
The schema should show order_date as date. Before the to_date call it was string. This is the type of check you should run after any change to a DataFrame.
Rows, columns and types
A row is an ordered record of values. A column is a named field with one data type across all rows. Common types you will meet are INT, BIGINT, DOUBLE, STRING, BOOLEAN, DATE, TIMESTAMP, DECIMAL(p, s), as well as nested ARRAY, MAP and STRUCT.
Unlike a pandas DataFrame, a Spark DataFrame has no meaningful row order and no row index. If you need an order, you must ask for it with orderBy. If you need a key, you must use a column. Position-based access such as "the third row" is not part of the model, because rows are spread over partitions that are processed in parallel.
Columns are referenced in three common ways:
| Form | Example | Notes |
|---|---|---|
| String name | `"amount"` | Works in `select`, `groupBy`, `drop` and many functions. |
| `F.col` | `F.col("amount")` | Needed to build expressions such as `F.col("amount") > 50`. |
| Attribute or index | `orders.amount`, `orders["amount"]` | Ties the column to one DataFrame. Useful in joins, but breaks on names with spaces or that clash with DataFrame methods. |
DataFrames compared with neighbors
| Concept | Where it lives | Key difference |
|---|---|---|
| Spark DataFrame | Distributed across the cluster | Lazy, immutable, no row order |
| pandas DataFrame | Memory of one machine (the driver) | Eager, mutable, has an index |
| SQL table or view | Catalog or session | Same engine. A DataFrame and a SQL query over the same data compile to the same kind of plan |
| RDD | Distributed | Lower-level API with no schema. Prefer DataFrames |
Because DataFrames and SQL share the same engine, the choice between them is mostly about readability. A later chapter shows how to move between them with temporary views.
Common errors
- Ignoring the return value.
orders.withColumn("x", F.lit(1))on its own line changes nothing. Assign the result. - Expecting data from a variable. Printing
ordersshows onlyDataFrame[order_id: int, ...], which is the schema, not the rows. Usedisplayorshow. - Assuming order.
show()on an unordered DataFrame can return rows in a different order on a different run or cluster size. - Misreading types. A column that looks like a date but is a
stringwill sort and compare as text. CheckprintSchema()first. - Name mismatch. Column names are case-insensitive by default in Spark SQL, but treating them as case-sensitive in your code keeps it portable and avoids ambiguity.
Check your understanding
Exercise
You run orders.filter(F.col("amount") > 50) on its own line in a cell, then in the next cell run display(orders). Does the second cell show only the rows with amount above 50? Explain why, and give the fix if you wanted that result.
Show answer
No. DataFrames are immutable, so filter returns a new DataFrame and leaves orders unchanged. Also, the first cell did no work, because it only built a plan and was never followed by an action. The fix is to assign the result, for example big = orders.filter(F.col("amount") > 50), and then call display(big).
Exercise
Why does a Spark DataFrame have no "third row" in the way a pandas DataFrame does, and what do you do when you need a defined order?
Show answer
A Spark DataFrame is split into partitions that are processed in parallel, so rows have no guaranteed position. When you need an order, you request it explicitly with orderBy on one or more columns, and when you need a row identifier you store it in a column.