Sub topic 10
Applying your own pandas code with map_partitions
This chapter covers map_partitions, the method that runs your own pandas function on every partition of a Dask DataFrame. It assumes you know basic Python functions and imports, and pandas fundamentals such as assign, filtering, and groupby. It also assumes you have met partitions, lazy evaluation, and compute from earlier chapters.
Why map_partitions exists
A Dask DataFrame is a collection of pandas DataFrames, called partitions. Most pandas methods have a Dask version that works on this collection. Sometimes the logic you need has no Dask equivalent, or it is easier to write as one pandas function. map_partitions covers those cases.
The method takes a function and calls it once per partition. Each call receives an ordinary pandas DataFrame and returns a pandas object. Dask stitches the results back together into a new Dask DataFrame. Like other Dask operations, it is lazy. Nothing runs until you call compute() or persist().
The key property is independence. Each call sees only its own partition. This makes map_partitions cheap, because no data moves between workers. It also limits what the function can do correctly.
A first example
The example below builds a small DataFrame and adds a column of fares in cents. The function is plain pandas.
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())You can test the function without Dask at all, by calling add_fare_cents(pdf). This is a useful habit. If the function works on a pandas DataFrame, any failure inside map_partitions points to Dask behavior and not to your logic.
Passing extra arguments
Positional and keyword arguments after the function are forwarded to every call.
def add_tax(part, rate, column="fare"):
return part.assign(**{f"{column}_with_tax": part[column] * (1 + rate)})
ddf3 = ddf.map_partitions(add_tax, 0.2, column="fare")
print(ddf3.compute())Dask treats arguments that are Dask collections specially. If you pass another Dask DataFrame that has the same partitioning, Dask pairs up the matching partitions. Plain Python values such as numbers and strings are passed unchanged to every call.
Metadata: telling Dask what comes out
Dask must know the column names and dtypes of the result before it computes anything. This description is called meta. It lets Dask print the DataFrame, check later column references, and build the rest of the graph.
If you do not supply meta, Dask runs your function on a small fake frame. The fake frame has the right columns and dtypes but contains placeholder values. The output of that call becomes the meta.
This inference works for simple functions. It can fail or guess wrong in these cases:
- The function raises an error on placeholder data, for example when it parses strings or divides by values.
- The function output depends on the real values, such as a column whose dtype changes with the data.
- The function is slow, so the extra call costs time.
In those cases, pass meta yourself. The simplest form is an empty pandas DataFrame with the correct columns and dtypes.
meta = ddf._meta.assign(fare_cents=pd.Series(dtype="int64"))
ddf4 = ddf.map_partitions(add_fare_cents, meta=meta)
print(ddf4.dtypes)ddf._meta is the empty frame Dask already holds for the input. You can also pass a dictionary such as {"zone": "object", "fare": "float64", "fare_cents": "int64"} or a list of (name, dtype) tuples. Whichever form you use, the dtypes must match what the function really returns.
Functions that return something other than a DataFrame
The function may return a Series, a scalar, or another object. Dask needs meta to describe it.
For a Series, pass a pd.Series with the right name and dtype, or a tuple like ("fare_cents", "int64").
def fare_in_cents(part):
return (part["fare"] * 100).astype("int64")
cents = ddf.map_partitions(fare_in_cents, meta=("fare", "int64"))
print(cents.compute())A function that returns one number per partition is a handy way to inspect partitions. Each result is a single value, so the output is a Dask Series with one row per partition.
def rows_in_part(part):
return pd.Series([len(part)])
sizes = ddf.map_partitions(rows_in_part, meta=(None, "int64"))
print(sizes.compute())This shows how rows are spread across partitions. Uneven sizes often explain slow runs, a topic for the partition sizing chapter.
What the function must not assume
Because each call sees one partition, operations that need the whole dataset give wrong answers without raising errors. This is the most important edge case in this chapter.
| Operation inside the function | What happens |
|---|---|
| Row-wise math, string cleaning, type casts | Correct. Each row depends only on itself. |
| `part["fare"].mean()` | Returns the mean of one partition, not of the dataset. |
| `part.sort_values("fare")` | Sorts within each partition only. The combined result is not globally sorted. |
| `part.drop_duplicates()` | Removes duplicates inside one partition. Duplicates across partitions stay. |
| `part.groupby("zone").sum()` | Gives partial sums per partition. The same zone appears in several outputs. |
| `part["fare"].rank()` or `cumsum()` | Restarts in every partition. |
A short demonstration of the mean problem:
def center_fare(part):
return part.assign(fare_centered=part["fare"] - part["fare"].mean())
wrong = ddf.map_partitions(center_fare).compute()
right = pdf["fare"] - pdf["fare"].mean()
print(wrong["fare_centered"].tolist())
print(right.tolist())With two partitions, each one is centered on its own mean, so the two lists differ. The fix is to compute the global value first and pass it in as an argument.
overall_mean = ddf["fare"].mean().compute()
def center_with(part, mean):
return part.assign(fare_centered=part["fare"] - mean)
fixed = ddf.map_partitions(center_with, overall_mean)
print(fixed.compute()["fare_centered"].tolist())The pattern is: compute a small global summary with Dask, then broadcast it into a per-partition function. For aggregations, prefer the built-in Dask groupby. It combines partial results correctly.
Partitions are not guaranteed to be tidy
Your function may receive an empty partition, for example after a selective filter. It should return an empty frame with the right columns instead of failing. Code such as part["fare"].iloc[0] breaks on an empty partition.
Dask may also call the function on a fake or empty frame to infer meta, as described above. Do not put side effects in the function when you rely on inference. Writing files, appending to lists, or printing a counter would run more times than the number of partitions. If you need side effects, pass meta explicitly and write the function so that repeated or empty calls are harmless.
Choosing between map_partitions and other tools
- Use ordinary Dask DataFrame methods when they exist. They handle cross-partition logic and need no
meta. - Use
map_partitionsfor row-wise or partition-local logic that is easier to write in pandas. - Avoid
apply(..., axis=1)on a Dask DataFrame for heavy row logic when you can write a vectorized pandas function and usemap_partitions. Vectorized pandas code runs once per partition, not once per row in Python. - For logic that needs global context, compute a small summary first, or use a shuffle-based operation covered in a later chapter.
Debugging a map_partitions function
Errors from workers can be hard to read. A reliable routine has three steps:
- Take one partition with
ddf.get_partition(0).compute()and call your function on it directly in pandas. - Run the whole computation with the synchronous scheduler,
result.compute(scheduler="synchronous"). Errors then appear in the main thread, and you can usepdbor a debugger. - If the error mentions
meta, check the dtypes you declared against the real output.
part0 = ddf.get_partition(0).compute()
print(add_fare_cents(part0))
print(ddf2.compute(scheduler="synchronous"))Exercise
A teammate writes ddf.map_partitions(lambda p: p.sort_values("fare")) and then takes .head(3) expecting the three smallest fares in the dataset. Why can this be wrong, and what would you do instead?
Show answer
The lambda sorts each partition on its own, so the combined data is not globally sorted. head(3) reads only the first partition, so it returns the three smallest fares of that partition, not of the dataset. Use a Dask method that sees all partitions, such as ddf.nsmallest(3, "fare"), or ddf.sort_values("fare") if a full global sort is needed, accepting that a global sort requires a shuffle.
Exercise
Your function converts a text column to numbers and raises an error when map_partitions runs without meta, even though it works on real data in pandas. What is the likely cause and the fix?
Show answer
Without meta, Dask runs the function on a small fake frame with placeholder values, and the conversion fails on them. Pass meta explicitly, for example an empty DataFrame with the expected output columns and dtypes, so Dask skips the inference call.