Sub topic 6
Filtering, assigning and aggregating the pandas way
This chapter assumes you know pandas boolean masks, assign and groupby, and that you have built a Dask DataFrame with dd.from_pandas and called compute(). Most pandas code works on a Dask DataFrame with little or no change. The differences come from partitions and laziness.
Filtering
A boolean mask works as it does in pandas. Dask applies it to every partition separately, so no data moves between partitions.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b", "a", "c"],
"fare": [10.0, 20.0, 30.0, 40.0, 15.0, 25.0],
"tip": [1.0, 2.0, 0.0, 5.0, 1.5, 2.5],
})
ddf = dd.from_pandas(pdf, npartitions=3)
expensive = ddf[ddf["fare"] > 15]
print(expensive.npartitions) # still 3, some may now be small or empty
print(expensive.head()) # computes only the first partitionFiltering does not change the partition count. A selective filter can leave many small or empty partitions. The partition sizing chapter covers how to fix that.
Assigning columns
Dask objects are not changed in place. Use assign or item assignment to build a new column. Both return a new lazy object or rebind the name, and neither runs any computation.
ddf = ddf.assign(tip_rate=ddf["tip"] / ddf["fare"])
ddf["total"] = ddf["fare"] + ddf["tip"]
print(ddf.columns.tolist())Operations that depend on row position or on global order are the ones to avoid. Dask does not support row selection with iloc, for example, because no partition knows its global row position.
Aggregating with groupby
A groupby aggregation computes a partial result in each partition. It then combines the partial results in a tree, so the final answer is small.
stats = ddf.groupby("zone")["fare"].agg(["sum", "count", "mean"])
print(stats.compute())Plain sum, mean, count, min and max are cheap because the combined result is small. By default Dask puts the result in one partition. For a high-cardinality key, where there are millions of distinct groups, pass split_out so the result stays spread over several partitions.
by_zone = ddf.groupby("zone")["fare"].mean(split_out=2)
print(by_zone.npartitions) # 2Which calls trigger computation
Some familiar pandas calls compute immediately, because they need a real value.
| Call | Behavior |
|---|---|
| `ddf["fare"] > 15` | Lazy, builds the task graph |
| `ddf.groupby("zone")["fare"].mean()` | Lazy |
| `len(ddf)` | Computes at once, reads all partitions |
| `ddf.head()` | Computes the first partition only |
| `ddf["fare"].sum().compute()` | Computes at once, returns a number |
Common errors
- Expecting data when printing. Printing a lazy object shows its structure, not its values. Call
compute()orhead(). - Using Python
ifon a lazy value.if ddf["fare"].sum() > 100:fails or misleads, because the value is not computed yet. Compute it first. - Row-by-row loops. Looping over rows pulls data back to one process and loses all parallelism. Use column expressions instead.
- Counting on row order. Order across partitions follows the index. Do not assume it matches pandas row positions after filters.
Exercise
Given the Dask DataFrame ddf above, write code that keeps rows where tip is above 1, adds a tip_pct column equal to tip / fare * 100, and returns the mean tip_pct per zone as a pandas object.
Show answer
tippctbyzone = ddf[ddf["tip"] > 1].assign(tippct=lambda d: d["tip"] / d["fare"] * 100).groupby("zone")["tip_pct"].mean().compute()
Exercise
Why does ddf[ddf["fare"] > 15].npartitions equal ddf.npartitions, even if the filter removes most rows?
Show answer
The mask is applied inside each partition and does not move data between them, so the partition count stays the same. Some partitions may become small or empty.