Sub topic 2
Running the Work with Dask DataFrames
Assume basic Python, pandas, and familiarity with memory limits on one machine. Dask DataFrames use lazy evaluation, which means operations build a task graph instead of running immediately. A task graph records the work Dask must perform.
Running the Work: `compute` and `persist`
compute() executes a lazy Dask object and returns an in-memory result, usually a pandas object. Use it when you need the final value.
persist() executes the graph and keeps the resulting partitions in memory. Use it when several later calculations reuse the same transformed data.
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(mean_fare) # Lazy Dask Series
result = mean_fare.compute() # Executes the graph
print(result)
ddf = ddf.persist() # Cache computed partitions
total, count = ddf["fare"].sum(), ddf["fare"].count()
print(total.compute(), count.compute())Filtering, Assigning, and Aggregating
Most pandas-style expressions work on Dask DataFrames. Dask applies simple operations independently to partitions, then combines partial results when necessary. Aggregations such as groupby().mean() can require coordination across partitions.
Reading and Writing Parquet
Parquet is a column-oriented file format. Dask commonly stores each partition as a separate file. Selecting columns reduces disk and memory use.
ddf.to_parquet("out/fares.parquet", write_index=False)
subset = dd.read_parquet(
"out/fares.parquet",
columns=["zone", "fare"],
)
print(subset.npartitions)Choosing a Scheduler
A scheduler decides how Dask runs the task graph.
| Scheduler | Useful when |
|---|---|
| `threads` | pandas and NumPy operations release the GIL |
| `processes` | Python code is CPU-bound |
| `synchronous` | Debugging errors step by step |
print(mean_fare.compute(scheduler="threads"))
print(mean_fare.compute(scheduler="synchronous"))A distributed Client provides workers and a dashboard for monitoring tasks and memory.
Exercise
When should you use persist() instead of calling compute() once?
Show answer
Use persist() when multiple later computations reuse the same transformed Dask DataFrame; it computes the partitions once and keeps them available.