Sub topic 5
Running the work: compute and persist
This chapter assumes you know pandas basics (filtering, assign, groupby), and that you have seen how a Dask DataFrame is split into partitions and how lazy evaluation builds a task graph. Here you will learn how to trigger that graph, what you get back, and when to keep results in memory.
What compute does
Operations on a Dask DataFrame return lazy objects. A lazy object holds a recipe, not data. Calling .compute() runs the recipe and returns an ordinary in-memory result: a pandas DataFrame, a pandas Series, or a Python scalar.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
mean_fare = ddf[ddf["fare"] > 15].groupby("zone")["fare"].mean()
print(type(mean_fare)) # a lazy Dask object, nothing computed yet
result = mean_fare.compute() # runs the task graph and returns a pandas object
print(result)The filter and the groupby only build the graph. compute() executes it, and result is a pandas Series indexed by zone.
Two consequences follow from this:
- The result must fit in the memory of the process that called
compute(). Dask can process data much larger than memory, but the object you get back is a normal pandas object. - Each
compute()call runs the whole graph from the data source. Dask does not remember earlier results unless you ask it to.
Keep results small
A common mistake is calling compute() on a large DataFrame, such as ddf.compute() on a big dataset. That concatenates every partition into one pandas DataFrame in your process. If the data was too large for pandas to begin with, this fails with a memory error.
Reduce the data first, then compute. Aggregations, filters that remove most rows, and head() all produce small results.
| Call | What you get | Memory risk |
|---|---|---|
| `ddf.compute()` | Entire dataset as one pandas DataFrame | High |
| `ddf["fare"].sum().compute()` | One number | Very low |
| `ddf.groupby("zone")["fare"].mean().compute()` | One row per group | Low unless there are millions of groups |
| `ddf.head()` | First rows of the first partition | Low |
head() looks at only the first partition by default. If that partition has fewer rows than requested, you get fewer rows and a warning. Pass npartitions=-1 to search all partitions, but that costs more.
The repeated-work problem
Because each compute() starts from the source, two computations that share an expensive step both pay for it.
Suppose ddf comes from reading and cleaning a large set of CSV files. Computing a sum and then a count reads and cleans the files twice.
total_value = ddf["fare"].sum().compute()
count_value = ddf["fare"].count().compute()
# the source was read and processed two timesThere are two ways to fix this. You can compute several results in one call, or you can persist the shared data.
Computing several results together
dask.compute accepts many lazy objects and runs them as one graph. Dask merges the shared steps, so the common work happens once.
import dask
total = ddf["fare"].sum()
count = ddf["fare"].count()
total_value, count_value = dask.compute(total, count)
print(total_value, count_value)dask.compute returns a tuple in the same order as the arguments. Use this when you know all the results you need at the same time. It needs no extra memory beyond the results themselves.
What persist does
persist() runs the graph and keeps the resulting partitions in memory, but it still returns a Dask DataFrame. Later computations start from the stored partitions instead of the original source.
ddf = ddf.persist() # compute once and keep partitions in memory
total = ddf["fare"].sum()
count = ddf["fare"].count()
total_value, count_value = total.compute(), count.compute()After persist(), ddf is still a Dask DataFrame with the same partitions. The difference is that each partition is now materialized as a real pandas DataFrame held in memory. The two calls at the end reuse them.
The comparison with compute() matters:
| Row | `compute()` | `persist()` |
|---|---|---|
| Returns | pandas object or scalar | Dask object |
| Data location | Your local process | Memory of the workers |
| Result size | Must fit in one process | Must fit in total worker memory |
| Typical use | Final answer | Reused intermediate data |
With the default local schedulers, "memory of the workers" is the memory of your own machine. The benefit of persist() is greatest with a distributed Client, where partitions are spread across several worker processes or machines and persist uses their combined memory. The Client is covered in a later chapter.
Persist is eager only on a Client
With a distributed Client, persist() returns right away and the work continues in the background. The returned DataFrame holds futures, which are references to partitions that are being computed. Later operations wait for them as needed. With the plain local schedulers (threads or processes without a Client), persist() blocks until the work finishes.
You can call wait from dask.distributed to block until persisted data is ready, which helps when you time a step.
from dask.distributed import Client, wait
if __name__ == "__main__":
client = Client()
persisted = ddf.persist()
wait(persisted) # block until every partition is in memory
print(persisted["fare"].sum().compute())
client.close()When to persist
Persist when all of these hold:
- The dataset, or a reduced version of it, fits in memory across your workers.
- You will run several computations on it.
- Producing it is expensive: reading many files, a heavy filter, or a shuffle.
A typical pattern is to load, clean and filter the data, persist it, then explore it interactively with many small aggregations.
Do not persist in these cases:
- The data is larger than available memory. Workers will spill to disk or be killed.
- You use the data once. Persisting adds memory cost with no benefit.
- The data is cheap to recompute, for example a column selection from a Parquet file.
Persist after you have reduced the data, not before. Selecting needed columns and filtering rows first means less memory is held.
slim = (
ddf[["zone", "fare"]] # keep only needed columns
[ddf["fare"] > 0] # drop unwanted rows
.persist() # then keep the reduced data in memory
)Releasing memory
A persisted DataFrame stays in memory as long as a Python reference to it exists. When you reassign the name or delete it, Dask can release the partitions.
del slim # drops the reference, workers can free the partitionsIf you write ddf = ddf.persist() the old lazy object is replaced and the persisted one takes its place. If you instead write p = ddf.persist() and keep both names, only p holds data in memory. Computations on the original ddf still start from the source. This is a frequent source of confusion: if repeated work does not go away, check that you are using the persisted object.
Edge cases and gotchas
Computing a result that is not small. A groupby on a column with very many unique values returns one row per value. That can be huge. Check the size lazily first with ddf["zone"].nunique().compute().
Randomness. If a graph contains a random step, such as sample, computing twice can give different rows unless you set random_state. Persisting fixes one outcome in memory. Two separate compute() calls may not match.
Side effects in map_partitions. Dask may run a function more than once, for example on a fake input to infer output types, or when a task is retried. Do not rely on a function running exactly once per partition. Keep such functions free of side effects such as appending to a file.
Lazy errors. Because nothing runs until compute(), an error in an early step shows up only when you trigger the graph. The traceback can look far from the line that caused it. Computing small pieces with head() while you build the pipeline helps locate the problem.
Repeated compute() inside loops. Calling compute() in a Python loop over many columns or groups runs the graph once per loop turn. Collect the lazy objects in a list and pass them to dask.compute together instead.
columns = ["fare"]
lazy_means = [ddf[c].mean() for c in columns]
(means,) = [dask.compute(*lazy_means)]
print(means)Quick decision guide
- Need a final number or small table:
compute(). - Need several final results from the same data:
dask.compute(a, b, c). - Need to reuse a large intermediate dataset many times and it fits in memory:
persist(). - Unsure whether the result is small: reduce it first, or look at
head().
Exercise
You load 200 CSV files into a Dask DataFrame, clean it, and then need the row count, the mean of fare, and the maximum of fare. The cleaned data takes 20 GB and your cluster has 64 GB of worker memory. You also plan to run many more exploratory queries afterwards. Which approach would you use for the three numbers now, and what would you do for the later queries?
Show answer
Compute the three numbers in one call with dask.compute(ddf.shape[0], ddf["fare"].mean(), ddf["fare"].max()) so the file reading and cleaning happen once. For the later queries, call ddf = ddf.persist() after cleaning, because the 20 GB fits in 64 GB of worker memory and the data will be reused many times. Each later aggregation then starts from the in-memory partitions instead of re-reading the 200 files.
Exercise
A colleague writes p = ddf.persist() and then runs ddf["fare"].sum().compute() several times. The queries stay slow. Why, and how do you fix it?
Show answer
persist() returns a new Dask DataFrame that holds the in-memory partitions. The original ddf is unchanged and still points to the source, so each query recomputes from the files. Run the queries on p, for example p["fare"].sum().compute(), or reassign with ddf = ddf.persist().