Sub topic 13
Partition sizing and repartitioning
This chapter assumes you know basic pandas, you have built a Dask DataFrame from files or from pandas, and you understand that Dask operations are lazy until you call compute() or persist(). You should also know that a Dask DataFrame is a collection of pandas DataFrames called partitions.
Why partition size matters
Every partition becomes at least one task in the task graph. The scheduler spends a small, roughly fixed amount of time on each task, usually a fraction of a millisecond up to a few milliseconds. That overhead is the cost of deciding where a task runs, sending it to a worker, and recording its result.
This gives two failure modes:
- Too many small partitions. If a partition holds a few thousand rows, the useful work per task is smaller than the overhead. A DataFrame with 100,000 tiny partitions can spend most of its time scheduling. The graph itself also takes memory and time to build.
- Too few large partitions. If a partition holds several gigabytes, one worker needs that much memory for one piece, plus working space for the operation. Operations such as
groupbyor a sort can need two to three times the partition size. You also lose parallelism, because 4 partitions can keep at most 4 workers busy.
A common rule of thumb is to aim for partitions of about 100 MB in memory, within a range of roughly 50 MB to 500 MB. The right number depends on your machine. A useful check is that each worker should hold several partitions at once, at least as many as its threads, with room left for intermediate results.
Inspecting your current partitions
Before changing anything, look at what you have. npartitions gives the count. map_partitions(len) computes the row count per partition. Memory use per partition comes from pandas memory_usage.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "c", "d"] * 2500,
"fare": [10.0, 20.0, 30.0, 40.0] * 2500,
})
ddf = dd.from_pandas(pdf, npartitions=8)
print("partitions:", ddf.npartitions)
rows = ddf.map_partitions(len).compute()
print("rows per partition:", rows.tolist())
mem = ddf.map_partitions(
lambda part: pd.Series([part.memory_usage(deep=True).sum()])
).compute()
print("MB per partition:", (mem / 1e6).round(3).tolist())The deep=True argument matters. Without it, pandas counts only the pointers of object columns and not the Python strings they point to, so the total can be far too low.
For the whole DataFrame, you can also compute the total in one pass and divide by npartitions:
total_bytes = ddf.memory_usage(deep=True).sum().compute()
print(total_bytes / ddf.npartitions / 1e6, "MB per partition on average")Where partitions come from
The partition count is decided when data is loaded. It is not tuned for you later.
| Source | How partitions are chosen |
|---|---|
| `dd.from_pandas(pdf, npartitions=n)` | You pass `npartitions` (or `chunksize`). |
| `dd.read_csv(path)` | By default, one or more partitions per file, split by a byte block size. |
| `dd.read_parquet(path)` | Depends on the files and row groups. Often one partition per file. |
| After `filter` | Unchanged. Partitions stay, but each may become much smaller. |
| After `groupby().agg()` | Usually reduced to one or a few partitions, via a tree reduction. |
The filter row matters most in practice. If you read 1,000 partitions and then keep 0.1% of rows, you still have 1,000 partitions, each almost empty. Every later step pays full scheduling overhead for almost no data. This is the most common reason to repartition.
Repartitioning
repartition changes how rows are grouped into partitions. It has three common forms.
By target size
ddf = ddf.repartition(partition_size="100MB")
print(ddf.npartitions)Dask measures the memory use of the existing partitions and merges or splits them to approach the target. Because it must measure first, it can trigger computation of partition sizes. This form is usually the best default.
By count
ddf_small = ddf.repartition(npartitions=2)
print(ddf_small.npartitions)This sets the number of output partitions directly. Reducing the count is cheap, because Dask concatenates neighboring partitions without moving rows across the whole dataset. Increasing the count splits partitions, which is also done locally but yields uneven results if the original partitions were uneven.
By index divisions
If the DataFrame has a sorted index with known divisions, you can pass divisions=[...] to place boundaries exactly. This is useful when later operations such as joins or loc slicing depend on index ranges.
What repartition does and does not do
Repartitioning by size or count is a narrow operation. It combines or splits adjacent partitions, and it preserves row order. It does not sort or group rows by value. If you need all rows with the same key in the same partition, that is a shuffle (see the chapter on shuffles and joins), which is far more expensive.
Two other points follow:
- Repartitioning is lazy. It adds a step to the task graph. You pay when you call
compute()orpersist(). - Repartitioning costs something. If you repartition and then use the data once, you may pay more than you save. It pays off when the result is reused, or when it prevents a large number of tiny tasks downstream.
A worked example: filter, then repartition, then persist
The following example builds a DataFrame with many partitions, applies a selective filter, and compares the partition count before and after.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"id": range(100_000),
"fare": [float(i % 100) for i in range(100_000)],
})
ddf = dd.from_pandas(pdf, npartitions=50)
selected = ddf[ddf["fare"] > 98]
print("after filter:", selected.npartitions) # still 50
selected = selected.repartition(npartitions=2)
selected = selected.persist()
print("after repartition:", selected.npartitions) # 2
print("rows:", len(selected))The filter keeps about 1% of the rows, spread across all 50 partitions. After repartition(npartitions=2), there are two partitions of about 1,000 rows each, and persist() keeps them in memory so later steps start from the compact version.
Partition size and Parquet
When you write with to_parquet, each partition becomes its own file. Your partition layout at write time therefore decides your file layout, and the next reader's partition layout.
- Many tiny files slow down every later read, because each file needs a metadata lookup and a task. On cloud object storage this cost is larger.
- A few enormous files limit parallelism and memory headroom.
Repartition before writing, so the files are a reasonable size. Targets of 100 MB to 1 GB per file on disk are common for Parquet.
ddf = ddf.repartition(partition_size="100MB")
ddf.to_parquet("out/fares.parquet")When reading, newer Dask versions let you control how files are grouped into partitions. Check the dd.read_parquet documentation for your installed version, because the option names for splitting row groups or combining small files have changed between releases.
Edge cases and gotchas
- Memory estimates are approximate.
partition_sizeuses pandas memory estimates. Object and string columns are the least accurate, so check real worker memory on the dashboard. - Uneven partitions. After a filter, partitions can differ widely in size. Repartitioning by count does not equalize them. Repartitioning by
partition_sizehandles this better, because it measures first. - Unknown divisions. After many operations the index divisions become unknown. Size-based and count-based repartitioning still work, but index-based repartitioning does not.
- Over-merging. Setting
npartitions=1on a large dataset pulls everything into one partition on one worker, which can cause a memory error. Use it only when the data is known to be small. - Repartition inside loops. Calling
repartitionrepeatedly adds steps to the graph each time. Do it once, at a deliberate point.
A short checklist
- Check
npartitionsand the per-partition memory. - If there are thousands of near-empty partitions, repartition by size or count.
- If a few partitions are very large, split them so every worker has several to work on.
- Persist the result if you will reuse it.
- Repartition again before
to_parquetif the files would be badly sized.
Exercise
You read 2,000 partitions of about 100 MB each, then apply a filter that keeps 0.05% of the rows. You then run several groupby aggregations on the result, and the computations feel slow even though the data is tiny. What is the likely cause, and what two steps would you take?
Show answer
The filter leaves 2,000 partitions of about 50 KB each, so every later operation creates thousands of tasks whose scheduling overhead exceeds the work. Repartition after the filter, for example with repartition(partition_size="100MB") or repartition(npartitions=1) if the result is clearly small, and then persist() the result so the aggregations reuse the compact data in memory.
Exercise
Why is repartition(npartitions=10) not a substitute for a shuffle when you need all rows with the same zone value in one partition?
Show answer
Repartitioning by count or size only merges or splits neighboring partitions and keeps row order. It does not move rows based on their values. Grouping rows by key requires a shuffle, such as set_index on the key column, which sends rows between workers and costs much more.