Sub topic 4
Lazy evaluation and task graphs
This chapter assumes you know pandas DataFrames (selecting, filtering, assign, groupby) and have read the previous chapters on partitions and on creating Dask DataFrames. Here you will see what Dask does when you write an operation, and why nothing seems to happen.
Operations build a plan, not a result
In pandas, each line runs immediately. In Dask, operations on a DataFrame are lazy. Dask records what you asked for and returns a new lazy object. The data is not read or processed at that point.
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 yetThe filter and the groupby only describe work. Printing mean_fare shows its structure (a name, a dtype, the number of tasks), not values.
What a task graph is
The recorded plan is a task graph. It is a directed graph where each node is a small task, such as "filter partition 0", and each edge says that one task needs the output of another.
Because every partition is a separate pandas DataFrame, most steps split into one task per partition. Those tasks do not depend on each other, so they can run in parallel. A final task combines the partial results.
Notice that a mean is not computed by averaging per-partition means. Dask keeps partial sums and counts and combines them, which gives the correct answer.
Why Dask is lazy
Laziness gives Dask three advantages:
- Optimization. Dask sees the whole plan before running it. It can fuse adjacent steps into one task and skip work that no result depends on.
- Parallelism. Independent tasks can be scheduled across threads, processes, or machines.
- Memory control. Dask can process one partition at a time and discard intermediate data, so the full dataset never has to fit in memory.
Inspecting a graph without running it
You can examine the plan safely, because these calls compute no data:
print(mean_fare.npartitions) # partitions in the result
print(mean_fare.dask) # the graph of tasks
mean_fare.visualize() # draws the graph (needs graphviz)visualize() requires the graphviz package and system library. If they are missing, print(mean_fare.dask) is enough to see the task layout.
Common errors
- Expecting values. A lazy object does not hold data.
print(mean_fare)shows structure only. Running the graph is the job ofcompute(), covered in the next chapter. - Treating lazy objects like pandas. Code such as
if ddf["fare"].sum() > 100:does not work as you expect, because the sum is a lazy object, not a number. You need the computed value first. - Assuming errors appear early. A bug in your data, such as a bad value or a missing file, may only surface when the graph runs, even though the line that caused it ran long before.
Exercise
You run result = ddf[ddf["fare"] > 15]["fare"].sum() on a 50 GB dataset and the line returns instantly. Is this a sign that something is wrong? Explain what result holds.
Show answer
No. The line is lazy, so it only builds a task graph. result holds a lazy Dask object that describes the filter and the sum, and no data has been read or summed yet. The work happens when you call result.compute().
Exercise
Why does Dask compute a mean from partial sums and counts instead of averaging the mean of each partition?
Show answer
Partitions can have different numbers of rows. An average of per-partition means would weight small partitions too heavily and give a wrong result. Combining sums and counts gives the exact mean.