Spark DataFrames are immutable. Once you create a DataFrame, you cannot change its rows or columns in place — every "modification" you write returns a new DataFrame that shares the original's lineage and leaves the source untouched. That single fact explains most of the surprising behavior people hit when they try to treat a Spark DataFrame like a pandas DataFrame.
The confusion is understandable, because the word "mutable" gets applied to several different things in Spark: the DataFrame object, the data it represents, and the underlying storage. Only the last of those can genuinely change. This article separates those layers, shows what actually happens when you "update" a DataFrame, and covers the cases where mutability does apply.
What immutability means for a Spark DataFrame
An immutable object is one whose observable state cannot change after creation. In Spark, a DataFrame is a description of a distributed computation — a logical plan over data — not a container of values you can reach into and edit. When you call withColumn, filter, or drop, the original variable still refers to the same logical plan, and Spark hands you a new DataFrame representing the new plan.
That design is deliberate. Spark's Catalyst optimizer and Tungsten execution engine analyze your whole pipeline before running anything, and they rely on the guarantee that a given DataFrame's definition will not shift underneath them. If a DataFrame could be mutated mid-pipeline, cached plans, reused references, and parallel tasks would all risk reading inconsistent data.
Immutability also makes DataFrame operations thread-safe in a specific sense: multiple threads can reference the same immutable DataFrame and derive different results without interfering with one another. What is not safe is sharing a mutable object like a DataFrameWriter or a custom accumulator casually across threads — that's a different concern.
A quick grounded rule: assigning a new result to a variable is rebinding the variable, not mutating the DataFrame. The old plan still exists as long as something references it.
Why "mutable" is ambiguous in Spark
People say Spark DataFrames are mutable when they really mean one of three things, and untangling them removes most of the confusion.
| Layer | Can it change? | What it looks like |
|---|---|---|
| DataFrame object / logical plan | No | df.withColumn(...) returns a new DataFrame; df is unchanged |
| Row values within a partition at execution time | No, not observably | You cannot write df[0]["col"] = x and have it stick |
| Underlying storage (files, tables, Delta/Iceberg tables) | Sometimes | INSERT, UPDATE, MERGE, overwrite writes, and CREATE OR REPLACE change stored data |
| Variables and collections you build yourself | Yes | A Python dict or list you use to construct a DataFrame stays mutable |
So the precise answer: the DataFrame abstraction is immutable, but the dataset it points at may be mutable if it lives in a format or catalog that supports mutations, and the Java/Python objects you use to build DataFrames are ordinary mutable objects.
What immutability does not mean
It does not mean the data can never change in storage. It does not mean you cannot perform updates in Spark SQL — you can, through table operations. And it does not mean every operation allocates a full copy of your data, because Spark mostly works with lazy plans and narrow transformations rather than physically duplicating rows.
What actually happens when you "modify" a DataFrame
Here's the mechanism. Spark transformations are lazy: withColumn, select, filter, join, and similar calls build up a new logical plan without touching any data. Only an action triggers execution. When execution runs, Spark computes results from the source data according to the combined plan — the source is read, not edited.
python df = spark.read.parquet("/data/orders") df2 = df.withColumn("total", df.price * df.qty)
df is unchanged; df2 is a new DataFrame.
df still has no "total" column.
df.columns # [...] no 'total' df2.columns # [... 'total']
Reading df.columns after the withColumn call returns the original column list, because nothing changed. df2 is a distinct plan built from df. If you now cache df and reuse it, Spark can share the materialized partitions between the two plans — but df itself is still immutable.
A second subtlety: a filter or withColumn applied to df does not modify df for anyone else, but it also does not isolate you from later storage changes. If the parquet files under /data/orders are overwritten between two actions on df, the next read can see different data. That's storage mutability, not DataFrame mutability — a distinction that causes real bugs in long-running jobs.
A worked sequence
- Read
dffrom a table. df1 = df.filter("status = 'shipped'")— plan only.df2 = df1.withColumn("net", df1.amount - df1.refund)— plan only, derived fromdf1.df2.write.mode("overwrite").parquet(...)— action; reads source, writes new files.dfanddf1are still valid, still point at the original source, and still produce their original results unless storage changed.
If step 4 overwrote the same path df reads from, then any future action on df reads the new files. The DataFrame object never changed; the files did.
The mutable cases that actually exist
Saying "Spark is immutable" too broadly would be misleading, because real mutation workflows exist at the table and storage layer.
Spark SQL table operations. In a lakehouse table format or a Hive-managed table, statements like INSERT INTO, INSERT OVERWRITE, UPDATE, DELETE, and MERGE change stored data. These are supported in Apache Spark's SQL engine and in the transactional table formats built on top of it. They write new files and update table metadata rather than editing partitions in place, but the effect is a mutable dataset.
sql UPDATE orders SET status = 'shipped' WHERE status = 'packed'; MERGE INTO orders t USING staging s ON t.id = s.id WHEN MATCHED THEN UPDATE SET *;
Overwrite writes. df.write.mode("overwrite").save(path) replaces the data at a path. That's genuine mutation of storage, and it's one of the most common ways people accidentally change what an earlier DataFrame read.
Delta and Iceberg tables. Transactional formats add ACID guarantees, time travel, and schema evolution. You can update rows in place logically and even query an older version — but each version is an immutable snapshot, which keeps readers consistent. This is the elegant reconciliation: the table is mutable, but each version of it is an immutable snapshot.
Self-mutable Spark objects. Some APIs, like DataFrameWriter, are configured via chained method calls that return the same builder object. The builder is mutable; the DataFrame it writes is not.
Why Delta and Iceberg feel mutable
If you write MERGE into a Delta table, you can then read the table and see updated rows. That does not contradict immutability — Spark wrote a new set of files and a new table log entry atomically. The old files still exist until compaction removes them. The reader always sees a consistent snapshot. This is why connector authors can honestly say "the DataFrame is immutable" and "the table supports updates" in the same breath.
Immutability and performance
Immutability is not just a philosophical stance — it enables the performance you paid for.
Because Spark knows a DataFrame's plan won't change during execution, Catalyst can push filters and projections down to the data source, reorder joins, prune partitions, and plan whole-stage code generation. A partially executed mutable object would make that optimization unsafe, because the optimizer couldn't reason about what the data looks like at execution time.
Caching follows the same logic. df.cache() materializes partitions from an immutable plan, so the cache is a consistent, reusable snapshot of that plan's output. If DataFrames were mutable, a cached partition could silently become stale. Time travel and lineage tracking exist for the same guarantee: snapshots of immutable versions.
The cost of immutability is that a naive update path can read and write a lot of data. Spark is not a row-store OLTP database; a whole-table overwrite to change one row is expensive. Understanding this trade-off is the practical point of the whole topic.
Practical patterns for updating data in Spark
Because you can't edit a DataFrame in place, "updates" are expressed by building a new DataFrame and then persisting it, typically through a transactional table.
Overwrite the whole table. Simplest and cheapest for small data or full refreshes. Compute the transformed DataFrame and write with mode("overwrite"). The trade-off is full rewrite cost and a brief lock on the table.
Use MERGE for row-level changes. In Delta or Iceberg, you stage a DataFrame of changed rows and merge it into the target. This is the right tool when you need to update a subset efficiently and get ACID behavior.
Use INSERT INTO with merges for append-only streams. For event data, appending new records is often a better model than updating rows at all. Append-only design sidesteps immutability arguments entirely because nothing is ever "changed."
Do a careful overwrite with a new path, then swap. If you don't have transactional tables, write to a fresh directory, validate it, and then swap the path your jobs read. This is a manual approximation of an atomic swap and avoids readers seeing intermediate states.
Avoid "partial update" patterns that don't exist. There's no supported in-place row edit on a plain parquet DataFrame. Any advice suggesting you can set a single value in a Spark DataFrame is describing a pandas-like mental model that Spark does not implement. (Spark's mapInPandas and applyInPandas let you run pandas or Arrow code per partition, but the input is still read-only from Spark's perspective, and you must return a new structure.)
Common misconceptions and how to avoid them
A few practical traps follow directly from misunderstanding immutability.
Trap 1: Assuming iteration updates a DataFrame. Writing for row in df.collect(): row.x = 1 changes local row objects, not the DataFrame. The next action on df is unchanged.
Trap 2: Reusing a variable and expecting the original. df = df.withColumn(...) rebinds the variable; anyone else holding the previous reference keeps the old plan. This is usually what you want, but in shared code it can surprise a caller.
Trap 3: Caching a DataFrame, then mutating its source table. The cache may serve the old, materialized data while a fresh DataFrame reads the new table. If consistency matters, design the pipeline so the cached snapshot is the intended one, or refresh and rebuild deliberately.
Trap 4: Expecting row-level deletes on raw parquet data without a table format. Plain parquet files can't be edited row by row; you must rewrite. If you need updates and deletes, use Delta, Iceberg, or Hive tables with the appropriate configuration.
Trap 5: Confusing DataFrameWriter mutability with DataFrame mutability. A writer builder mutates itself as you chain options, but the DataFrame it eventually writes is still immutable.
The mental model to adopt
Treat a DataFrame as a recipe and the stored data as the ingredients. Writing a DataFrame produces a result; editing the DataFrame changes the recipe, and changing the ingredients on the shelf is a separate matter. This model keeps you honest about which operations are cheap (plan changes), which are expensive (writes), and which are genuinely unsafe (ungoverned overwrites of data that other readers depend on).
Where this matters in practice
Immutability is the reason Spark pipelines can be reasoned about, optimized, and rerun idempotently. A deterministic chain of transformations over an immutable input yields the same output, which is a precondition for reliable recovery and correct aggregation. If you need updates at scale, the right question is not "can I mutate a DataFrame" but "which table format and write pattern gives me safe mutation with acceptable cost."
Frequently Asked Questions
Can you edit a single row of a Spark DataFrame?
No. A plain Spark DataFrame has no in-place row-edit operation. You build a new DataFrame containing the change — for example, by joining it against a DataFrame of updated IDs — and then persist the result, ideally with MERGE into a transactional table.
Is my DataFrame going to change if another job overwrites its source files?
The DataFrame's definition won't change, but the data it reads can. Spark reads the source each time an action runs unless you cached it, so an overwrite of the underlying files between two actions can produce different results. Cache deliberately when you need a stable snapshot.
Do Delta Lake and Iceberg make DataFrames mutable?
No. They make tables mutable by storing new immutable snapshots and atomically switching the table version that readers see. Each snapshot remains immutable, which is what enables time travel and consistent reads.
Why does withColumn not change my original DataFrame?
Because withColumn is a transformation that returns a new DataFrame representing the old plan plus the new column. The original variable keeps pointing at the original plan. Assign the return value to keep the change.
Is a Spark DataFrame the same as a pandas DataFrame in this respect?
No. pandas DataFrames are mutable and mostly in-memory on one machine; Spark DataFrames are immutable, distributed, and evaluated lazily. Code that edits pandas rows in place usually needs a rewrite — often an explicit transformation into a new DataFrame — when ported.
Immutability is the property that lets Spark plan, cache, and rerun work confidently; when you need to change stored data, do it deliberately through the table and write layer, and let each DataFrame remain a trustworthy description of one computation.