Sub topic 5
Running the work: compute and persist
This chapter assumes you know pandas basics (filtering, groupby, aggregation) and that you have seen how a Dask DataFrame is split into partitions and builds a lazy task graph. Here you learn how to run that graph with compute() and how to keep results in memory with persist().
Lazy objects and what triggers work
Operations on a Dask DataFrame only add nodes to a task graph. No data is read or processed until you ask for a result. Two methods ask for it:
compute()runs the graph and returns an ordinary in-memory object, such as a pandas Series, a pandas DataFrame, or a Python number.persist()runs the graph and keeps the resulting partitions in memory. It returns a new Dask DataFrame that is backed by those stored partitions.
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 describe the work. The call to compute() executes it. The value in result is a pandas Series, so everything you know about pandas applies to it from then on.
The cost of repeated computation
Every compute() call runs the full graph from the original source. If two results share the same expensive first steps, such as reading and filtering a large file, each call repeats those steps.
Keeping data with persist
Use persist() when you will run several computations on the same intermediate data.
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()Notice that persist() returns a new object, so you assign it back to a name. After that, sum and count start from the stored partitions rather than from the source.
On a local scheduler, persist() blocks until the work is done. With a distributed Client, which a later chapter covers, it returns immediately and the work continues in the background on the cluster. Either way, the result stays a Dask DataFrame, and the data stays spread across partitions.
Compute several results together
If you need more than one result, you can ask for them in a single call. Dask merges the graphs and shares the common steps, so the source is read once.
import dask
total, count = dask.compute(ddf["fare"].sum(), ddf["fare"].count())
print(total, count)dask.compute takes any number of lazy objects and returns a tuple of results in the same order.
Choosing between them
| Method | Returns | Data location | Use it when |
|---|---|---|---|
| `compute()` | pandas object or scalar | Local process memory | The result is small and you want to use it directly |
| `persist()` | Dask DataFrame | Partitions in memory, possibly on workers | You will reuse a large intermediate result |
| `dask.compute(a, b)` | Tuple of results | Local process memory | You need several results that share work |
Common errors
- Persisting data that does not fit in memory. The workers slow down or fail. Persist after filtering or selecting columns, not on the raw data.
- Calling
compute()inside a loop. Each call reruns the graph. Collect the lazy objects and calldask.computeonce. - Forgetting to reassign. Writing
ddf.persist()withoutddf = ...throws away the in-memory version, so later steps reread the source. - Computing too early. Converting a large intermediate result to pandas with
compute()and then continuing in pandas gives up the parallelism.
Exercise
You call ddf["fare"].sum().compute() and then ddf["fare"].mean().compute() on a Dask DataFrame read from a large CSV file. The file is read twice. Give two ways to avoid the second read.
Show answer
Persist the DataFrame first with ddf = ddf.persist() and then compute both results from the in-memory partitions. Or build both lazy results and run them together with dask.compute(ddf["fare"].sum(), ddf["fare"].mean()), which shares the read step in one graph.