Sub topic 2
Partitions: a DataFrame made of many pandas DataFrames
This chapter assumes you can use pandas (selecting, filtering, assign, groupby) and that you know a single machine has a memory limit. Here you will learn what a partition is and why Dask's behavior follows from it. You will also learn how to inspect partitions and which problems come from partitioning.
The core idea
A Dask DataFrame is not one big table. It is an ordered collection of ordinary pandas DataFrames, called partitions, plus the bookkeeping that describes them. Each partition holds a contiguous block of rows and has the same columns and dtypes as every other partition.
This design gives Dask two abilities:
- Parallelism. Different partitions can be processed at the same time on different threads, processes, or machines.
- Out-of-core work. Only some partitions need to be in memory at once, so the full dataset can be larger than RAM.
Most Dask behavior you will meet later follows from this structure. A filter runs once per partition. A sum is computed per partition and then combined. A join may need to move rows between partitions.
Looking at partitions
The smallest way to see this is to split a pandas DataFrame yourself. dd.from_pandas does that, and the next chapter covers other ways to create Dask DataFrames in detail.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": list("abababab"),
"fare": [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0],
})
ddf = dd.from_pandas(pdf, npartitions=3)
print(ddf.npartitions) # 3
print(ddf) # column names and dtypes, no data
print(ddf.partitions[0].compute()) # one partition, as a pandas DataFrame
print(ddf.map_partitions(len).compute()) # number of rows in each partitionPrinting ddf shows the structure: the columns, their dtypes, and the number of partitions. It does not show rows, because Dask has not loaded or computed them. ddf.partitions[0] is itself a Dask DataFrame with one partition. Calling .compute() on it gives you a plain pandas DataFrame, which is the best way to look at what a partition really contains.
map_partitions(len) runs Python's len on each pandas partition and gives one number per partition. This is a quick check for how evenly the rows are spread. The counts add up to 8.
What Dask stores about the whole frame
Besides the partitions, the Dask object keeps a small amount of metadata that it can read without touching the data:
- Column names and dtypes. Every partition must match them.
- The number of partitions, available as
npartitions. - Divisions. These are the index boundaries between partitions.
Divisions are worth a closer look.
print(ddf.divisions) # npartitions + 1 index values
print(ddf.known_divisions) # True when the boundaries are knownWhen divisions are known, Dask knows that partition 0 holds index values from the first boundary up to (but not including) the second, and so on. The index must be sorted for this to hold. With that knowledge Dask can skip partitions it does not need, and it can line up two frames that share the same boundaries without moving data.
When Dask cannot know the boundaries, divisions is a tuple of None values, and known_divisions is False. This is the usual case when you read many CSV files. Each file has its own pandas index starting at 0, so the combined index is not a global ordering. Operations that depend on the index, such as .loc lookups by label and index-aligned joins, then cost more or behave differently. The chapter on shuffles, joins, and the index returns to this.
How operations use partitions
Operations fall into groups by how much partitions must communicate. The table summarizes the pattern. Later chapters cover the costs in detail.
| Kind of operation | Example | What happens across partitions |
|---|---|---|
| Row by row | `ddf["fare"] * 2`, `ddf[ddf["fare"] > 15]` | Each partition is handled alone. No data moves. |
| Reduction | `ddf["fare"].sum()`, `ddf["fare"].mean()` | Each partition produces a small partial result. Dask combines the partials. |
| Grouped aggregation | `ddf.groupby("zone")["fare"].mean()` | Per-partition partial results are combined in steps. Usually cheap when there are few groups. |
| Rearranging rows | `set_index`, sorting, a join on unsorted keys | Rows must move between partitions. This is a shuffle and is expensive. |
Here is a reduction at work. Dask effectively does the following, though you never have to write it:
partials = [part["fare"].sum() for part in (
ddf.partitions[i].compute() for i in range(ddf.npartitions)
)]
print(sum(partials)) # same as pdf["fare"].sum(), 360.0
print(ddf["fare"].sum().compute())The hand-written version computes each partition's sum and adds the results. Dask does the same thing, but it runs the per-partition steps in parallel and never needs the whole table in one place.
Filters do not rebalance partitions
A filter keeps the same number of partitions. It only removes rows from inside each one.
big = ddf[ddf["fare"] > 60]
print(big.npartitions) # still 3
print(big.map_partitions(len).compute()) # some partitions are now small or emptyAfter a selective filter you can end up with many tiny or empty partitions. Dask still creates one task for each, so a heavily filtered frame carries overhead that no longer matches the amount of data. When a filter removes most rows, consider repartition afterward. The partition sizing chapter shows how.
Partition size and count
The number of partitions is a trade-off:
- Too few partitions. There is little parallelism, and each partition may be too large to fit in memory alongside intermediate results.
- Too many partitions. Dask spends more time scheduling than computing. Every partition becomes at least one task, and each task has a small fixed cost.
A common rule of thumb is partitions of roughly 100 MB in memory, with several partitions per CPU core. Treat this as a starting point. Measure with ddf.memory_usage(deep=True).compute() or the dashboard, which a later chapter introduces.
sizes = ddf.map_partitions(lambda part: part.memory_usage(deep=True).sum())
print(sizes.compute()) # bytes used by each partitionThis example's partitions are a few hundred bytes, far too small to be worth the overhead. On a toy frame that is expected, but on real data it would signal that you have too many partitions.
Common mistakes
- Treating a Dask DataFrame like pandas for positional access. There is no global row number.
ddf.iloc[5]is not supported for rows, because Dask does not know how many rows earlier partitions hold without computing them. - Assuming the index is unique across partitions. After reading many files, the same index value can appear in several partitions.
- Splitting a small dataset. If the data fits in memory comfortably, pandas is often faster. Partitioning adds task overhead that only pays off at scale.
- Calling
compute()on a result that is still huge.compute()returns a pandas object in your session, so it must fit in memory. Compute small results such as aggregates, and write large results to files. - Writing code that depends on partition boundaries. The number and edges of partitions can change when you read different files or repartition. Results should not depend on them, except inside deliberate per-partition code.
Summary of the model
- A Dask DataFrame is an ordered list of pandas DataFrames with the same schema.
- Operations are applied to each partition and then combined, and some need data to move between partitions.
npartitions,divisions, andmap_partitions(len)reveal the layout without loading the data.- Filters keep the partition count and can leave you with small or empty partitions.
- Partition size is a trade-off between parallelism and scheduling overhead.
Exercise
You build ddf = dd.from_pandas(pdf, npartitions=4) from a pandas DataFrame with 1,000 rows, then run small = ddf[ddf["fare"] > 1000], which keeps only 3 rows. What is small.npartitions, and why might that be a problem on a much larger dataset? How would you see how the 3 rows are spread across partitions?
Show answer
small.npartitions is still 4, because a filter works inside each partition and does not merge them. On a large dataset, a selective filter can leave thousands of nearly empty partitions, and each one still costs a scheduler task, so overhead outweighs the work. Run small.map_partitions(len).compute() to get the row count of each partition. If most are empty, repartition the filtered frame to fewer partitions.
Exercise
Why does ddf.iloc[5] on a Dask DataFrame not return the sixth row the way it does in pandas?
Show answer
Dask stores rows in separate partitions and does not know how many rows each partition holds until it computes them. Without those lengths it cannot translate a global position such as 5 into a partition and an offset. Position-based row access across the whole frame is therefore not supported. To inspect rows, take a partition with ddf.partitions[i].compute() or use ddf.head().