Sub topic 3
Using a Client and the dashboard
Assume you know pandas DataFrames, Dask partitions, lazy evaluation, and compute(). A Client starts a local Dask cluster and selects the distributed scheduler. Its dashboard shows task progress, worker memory, and slow operations.
import pandas as pd
import dask.dataframe as dd
from dask.distributed import Client
client = Client(processes=False)
print(client.dashboard_link)
pdf = pd.DataFrame({"fare": [10, 20, 30, 40]})
ddf = dd.from_pandas(pdf, npartitions=2)
result = (ddf.assign(fare_cents=ddf["fare"] * 100)
["fare_cents"].sum()
.compute())
print(result)
client.close()Open the printed dashboard link while a larger computation runs. For simple debugging, use scheduler="synchronous" instead. It runs tasks in one thread, so tracebacks are easier to follow.
Applying custom pandas code
map_partitions sends each partition to a function that receives an ordinary pandas DataFrame. The function must return compatible results for every partition.
def add_band(part):
return part.assign(
band=part["fare"].map(lambda x: "low" if x < 25 else "high")
)
ddf2 = ddf.map_partitions(add_band, meta={
"fare": "int64",
"band": "object",
})
print(ddf2.compute())meta describes the output columns and dtypes without running the full computation. Providing it avoids unreliable dtype inference, especially when the function has conditional logic or returns an unusual structure.
Shuffles, joins, and partition sizing
A filter or column assignment usually works independently on each partition. A groupby, join, or set-index operation may require a shuffle, which moves rows between workers. Shuffles use network, memory, and temporary storage, so inspect the dashboard when they dominate runtime.
Keep partitions large enough to avoid scheduling thousands of tiny tasks, but small enough to fit comfortably in worker memory. Repartition by approximate memory size:
ddf = ddf.repartition(partition_size="100MB")Pitfalls and debugging
- Calling
compute()repeatedly can repeat expensive work. Usepersist()when several analyses reuse the same data. - Calling
len(ddf)or converting everything to pandas can exceed memory. - Check
ddf.npartitionsand inspect the dashboard for oversized partitions. - Use explicit
metawhen custom functions produce warnings or incorrect types.
Beyond DataFrames
dask.delayed builds graphs from ordinary Python functions. It is useful when your workflow does not fit DataFrame operations.
from dask import delayed
@delayed
def read_and_score(value):
return value * value
total = sum(read_and_score(x) for x in [2, 3, 4])
print(total.compute()) # 29Exercise
Which operation is likely to require a shuffle: filtering rows or joining on a column?
Show answer
Joining on a column, because matching rows may need to move between partitions.