Sub topic 6
Filtering, assigning and aggregating the pandas way
This chapter assumes you know pandas selecting, filtering, assign and groupby. It also assumes you have met partitions, lazy task graphs, and compute and persist from earlier chapters. Here you will apply familiar pandas code to a Dask DataFrame. You will also learn where the two differ and which differences cause errors.
The working model
A Dask DataFrame is a set of pandas DataFrames called partitions. Most pandas-style calls on it do not run anything. Each call adds tasks to a graph, one task per partition, and returns another lazy Dask object. Calling compute() runs the graph and returns a pandas object.
Operations fall into two groups:
- Row-wise operations work on each partition alone: filters, column selection,
assign, arithmetic, and string or date methods. Partitions never need to talk to each other, so they scale well. - Aggregations combine information across partitions:
sum,mean,groupby,nunique. Dask computes a partial result per partition, then merges the partial results in a reduction step.
The tutorial's running example uses a small frame with two 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)Filtering
Boolean filtering looks the same as in pandas.
expensive = ddf[ddf["fare"] > 15]
print(type(expensive)) # a lazy Dask DataFrame
print(expensive.compute()) # a pandas DataFrame with 3 rowsThe mask ddf["fare"] > 15 is a lazy Dask Series. Indexing with it builds a new task per partition. Each partition keeps its own matching rows.
Filtering does not rebalance the data. If only 1% of rows match, you still have the same number of partitions, and most of them are now very small. The [partition sizing chapter](#) covers fixing this with repartition. For now, remember that a heavy filter leaves many tiny partitions behind.
You can combine conditions with &, | and ~, and each condition needs parentheses, exactly as in pandas.
subset = ddf[(ddf["fare"] > 15) & (ddf["zone"] == "a")]
print(subset.compute())isin, between and notnull also work. So does query, which takes a string expression.
Assigning new columns
assign returns a new Dask DataFrame with extra columns, and it works per partition.
ddf2 = ddf.assign(
fare_with_tax=ddf["fare"] * 1.1,
is_long=ddf["fare"] > 25,
)
print(ddf2.compute())You can also write ddf["fare_with_tax"] = ddf["fare"] * 1.1. Dask supports this form, but it rebinds the name ddf to a new lazy object. The assign form makes that clear and chains better.
Two rules matter here:
- You can only combine columns that line up. Operations between Series from the same DataFrame are fine. Operations between Series from unrelated frames work only when Dask can tell the partitions match. Otherwise it may raise an error or do expensive alignment work.
- You cannot assign by position. There is no
ilocfor rows, and assigning into a row, as inddf.loc[3, "fare"] = 0, is not supported. Build the new column from an expression instead, for example withwhereormask.
capped = ddf.assign(fare=ddf["fare"].where(ddf["fare"] <= 30, 30.0))
print(capped.compute())Aggregating
Reductions over a whole column return a lazy scalar.
total = ddf["fare"].sum()
print(total.compute()) # 100.0Grouped aggregations follow the pandas pattern. This is the central example of the chapter.
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, the groupby and the mean all join one graph. Nothing runs until compute(). The result is a pandas Series indexed by zone.
How a groupby aggregation works
For mean, Dask cannot average the per-partition means, because partitions can have different sizes. Instead each partition computes a sum and a count per group. The reduction step adds the sums and counts, then divides. Dask does this in a tree, so a large number of partitions does not overload one task.
The diagram below shows the flow.
Common aggregations such as sum, count, min, max, mean, std and var use this partial-then-merge pattern. It is cheap when the number of groups is small.
Several aggregations at once
Use agg to compute multiple statistics in one pass over the data.
stats = ddf.groupby("zone")["fare"].agg(["sum", "mean", "max"])
print(stats.compute())Computing them together is faster than three separate compute() calls, because each separate call re-reads and re-processes the source data.
Many groups and the `split_out` option
By default, a groupby aggregation returns a result with a single partition. That is fine for a few hundred groups. When you group by something with millions of distinct values, such as user ID, the result itself may be large. Pass split_out to spread the result across several partitions.
by_zone = ddf.groupby("zone")["fare"].sum(split_out=2)
print(by_zone.npartitions)With split_out greater than 1, Dask must move group data between partitions, which is a shuffle. Use it only when the result is too big for one partition.
Sharing work between computations
Each compute() call runs its whole graph from the start. If you ask for two results from the same source in two calls, the source work runs twice. Two options avoid this.
Compute them together with dask.compute, which merges the graphs and shares common tasks.
import dask
total, count = dask.compute(ddf["fare"].sum(), ddf["fare"].count())
print(total / count)Or call persist() first, so the partitions stay in memory and later computations reuse them.
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()Use dask.compute when you know all your results up front. Use persist() when you will explore interactively and the data fits in memory.
Differences from pandas that cause errors
| pandas habit | Dask behavior | What to do instead |
|---|---|---|
| `df.iloc[5]` or `df.iloc[:, 0]` for rows | Row position selection is not supported | Use `loc` with index labels, or `head()` |
| `df.loc[i, col] = value` | In-place row assignment is not supported | Build a new column with `where` or `mask` |
| `df.sort_values("fare")` | Works, but needs a full shuffle | Sort only when you must, and sort after reducing |
| `df.shape[0]` | `shape` holds a lazy value for rows | Use `len(ddf)` or `ddf.shape[0].compute()` |
| `df.head()` | Reads only the first partition | Remember that the rows come from partition 0 only |
| `if ddf["fare"].sum() > 10:` | A lazy object has no truth value yet | Call `.compute()` first |
| `df.apply(f, axis=1)` | Works, but needs `meta` and is slow | Prefer vectorized expressions |
Errors you will meet
- Using a lazy value in plain Python. Writing
if mean_fare > 20:orfloat(total)on an uncomputed object fails or gives a confusing result. Callcompute()at the point where you need a real number. head()is not a sample. It looks only at the first partition, by default. If the data is sorted,head()can mislead you. Useddf.sample(frac=0.01).compute()for a random sample instead.len(ddf)is a full computation. It scans every partition. Avoid calling it in a loop.- Calling
compute()too early. If you compute a large intermediate result and continue in pandas, you may run out of memory. Keep the work lazy and compute only the small final result. - Large results.
ddf.compute()on a big frame loads everything into one pandas DataFrame in your session. Compute reductions, not raw data.
A complete example
This script chains a filter, new columns and a grouped aggregation, and computes two summaries together.
import dask
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b", "c", "c"],
"fare": [10.0, 20.0, 30.0, 40.0, 50.0, 60.0],
"tip": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
})
ddf = dd.from_pandas(pdf, npartitions=3)
clean = ddf[ddf["fare"] > 15].assign(
total=lambda d: d["fare"] + d["tip"],
tip_rate=lambda d: d["tip"] / d["fare"],
)
by_zone = clean.groupby("zone").agg({"total": "sum", "tip_rate": "mean"})
row_count = clean["total"].count()
by_zone_df, n_rows = dask.compute(by_zone, row_count)
print(by_zone_df)
print(n_rows)The lambda form in assign receives the intermediate frame, so the new columns can use the filtered data. The final dask.compute call runs both results in one pass.
Summary of rules
- Write filters,
assignandgroupbyas you would in pandas. - Treat every result as lazy until
compute()orpersist(). - Compute related results together with
dask.compute, orpersist()shared inputs. - Keep group counts small, or use
split_outknowing it adds a shuffle. - Compute small results, never raw data.
Exercise
A DataFrame has columns "city" and "sales" in 200 partitions. You write a = ddf.groupby("city")["sales"].sum().compute() and then b = ddf.groupby("city")["sales"].mean().compute(). What is wasteful about this, and how would you fix it?
Show answer
Each compute call runs the whole graph, so the data is read and processed twice. Fix it by running both in one pass, either with ddf.groupby("city")["sales"].agg(["sum", "mean"]).compute() or with dask.compute(sum_result, mean_result) on the two lazy results. If you will keep exploring the data, call persist() on ddf first, when it fits in memory.
Exercise
Why can Dask not compute a groupby mean by averaging each partition's mean, and what does it do instead?
Show answer
Partitions can hold different numbers of rows, so an average of averages gives the wrong answer. Dask computes a sum and a count per group in each partition, adds them in the reduction step, and divides the total sum by the total count.