Sub topic 10
Applying your own pandas code with map_partitions
This chapter assumes you know pandas well and have met Dask partitions, lazy evaluation, and compute() in earlier chapters. You will learn how to run your own pandas function on every partition of a Dask DataFrame.
Why map_partitions exists
Dask covers many pandas operations, but not all of them. Sometimes you have a function written for pandas that uses a library or a method Dask does not offer. map_partitions solves this. It calls your function once per partition. Each call receives an ordinary pandas DataFrame and returns a pandas object.
Because each partition is processed on its own, there is no data movement between partitions. This makes map_partitions cheap and fast compared with shuffles.
A first example
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)
def add_fare_cents(part):
# part is an ordinary pandas DataFrame
return part.assign(fare_cents=(part["fare"] * 100).astype("int64"))
ddf2 = ddf.map_partitions(add_fare_cents)
print(ddf2.compute())The call to map_partitions is lazy. It adds one task per partition to the task graph. Nothing runs until compute().
Extra arguments are passed through to your function:
def scale_fare(part, factor):
return part.assign(fare=part["fare"] * factor)
ddf3 = ddf.map_partitions(scale_fare, factor=1.1)
print(ddf3.compute())How Dask knows the output columns
Dask must know the column names and dtypes of the result before it runs anything. Later lazy steps depend on this, for example selecting ddf2["fare_cents"]. This description is called meta.
If you do not pass meta, Dask runs your function on a small fake frame with the right dtypes and records what comes back. This works for simple functions. It can fail or guess wrongly if your function raises an error on fake data or depends on real values.
In those cases, give meta yourself. It is an empty pandas DataFrame with the correct columns and dtypes.
meta = pd.DataFrame({
"zone": pd.Series(dtype="object"),
"fare": pd.Series(dtype="float64"),
"fare_cents": pd.Series(dtype="int64"),
})
ddf4 = ddf.map_partitions(add_fare_cents, meta=meta)
print(ddf4.dtypes)What your function must respect
Your function sees one partition, not the whole dataset. Keep these points in mind:
- A partition is a slice of the data. A function that computes
part["fare"].mean()returns the mean of that slice, not the global mean. - Partition boundaries are arbitrary. Do not assume a particular group is wholly inside one partition unless you have arranged that, for example by setting the index.
- The function should return a DataFrame or Series with a consistent structure on every partition. Mixed dtypes between partitions cause errors later.
- Avoid side effects such as modifying global state. The function may run in another process or on another machine.
Where it fits
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error during graph building about meta | Function fails on fake data | Pass `meta` explicitly |
| Wrong dtypes after `compute()` | Inferred `meta` differs from real output | Pass `meta` and cast inside the function |
| Results differ from pandas | Logic depends on rows in other partitions | Use Dask groupby, or arrange data first |
Exercise
You write ddf.map_partitions(lambda p: p["fare"] - p["fare"].mean()) and compare it with the same code in pandas. The results differ. Why?
Show answer
The mean is computed separately inside each partition, so each row is compared with its own partition's mean, not the global mean. Compute the global mean first with ddf["fare"].mean().compute() and pass it as an argument, or use ddf["fare"] - ddf["fare"].mean().