Sub topic 1
When pandas is not enough, and what Dask adds
Prerequisites
This chapter assumes you have the following:
- Basic Python, including functions and imports.
- pandas DataFrame fundamentals: selecting, filtering,
assign,groupbyand aggregation. - Some experience reading CSV files, and an idea of what a memory limit on a single machine means.
You do not need to know anything about Dask yet. This chapter explains when to reach for it and what it changes. Later chapters cover the mechanics.
What pandas does well, and where it stops
pandas keeps an entire DataFrame in the memory of one Python process. That design makes it fast and pleasant for data that fits comfortably in RAM. Indexing, joins and groupby operations run on in-memory arrays with well-tuned code, and the API is the one most data people already know.
Two limits show up as data grows.
- Memory. The whole dataset must fit in RAM, and you need room for intermediate results. A common rule of thumb is that pandas needs several times the file size in memory, often 5 to 10 times for operations that copy data. A 4 GB CSV can exhaust a 16 GB laptop in the middle of a
mergeor agroupby. - Compute. Most pandas operations run on one CPU core. On a machine with eight cores, seven sit idle while a slow aggregation runs. Because of the Python global interpreter lock (GIL), splitting the work across threads yourself rarely helps unless the underlying library releases the GIL.
These are different problems. A dataset can be too large for memory but fast enough once loaded. Another can fit in memory but take twenty minutes because of heavy per-row work. Dask addresses both, so it helps to know which one you have.
What Dask adds
Dask is a Python library for parallel computing. Its DataFrame component, dask.dataframe, offers a large subset of the pandas API on top of a different execution model.
- Partitions. A Dask DataFrame is a collection of smaller pandas DataFrames called partitions. Each partition is a normal pandas object, so most operations reuse pandas code you already trust. The next chapter covers partitions in detail.
- Lazy evaluation. Dask does not run an operation when you write it. It records the operation in a task graph, which is a map of small jobs and their dependencies. Nothing runs until you ask for a result.
- Parallel scheduling. A scheduler runs independent tasks at the same time on threads, processes, or machines. It can also run a task, pass its result on, and free memory, so the whole dataset never has to be in RAM at once.
- Scale-out. The same code can run on a laptop or on a cluster of many machines, because the scheduler is a separate component you can swap.
The practical result is that you can process a dataset larger than memory, using all your cores, with code that looks very close to pandas.
The same analysis in both libraries
This script creates three small CSV files, then computes the mean fare per zone with pandas and with Dask. The data is tiny so you can run it anywhere. The structure is the point.
import glob
import os
import dask.dataframe as dd
import pandas as pd
os.makedirs("data", exist_ok=True)
for i in range(3):
pd.DataFrame(
{"zone": ["a", "b"] * 500, "fare": range(1000)}
).to_csv(f"data/part-{i}.csv", index=False)
# pandas: load everything into one DataFrame, then aggregate
files = sorted(glob.glob("data/part-*.csv"))
pdf = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
print(pdf.groupby("zone")["fare"].mean())
# Dask: describe the same work, then run it
ddf = dd.read_csv("data/part-*.csv")
result = ddf.groupby("zone")["fare"].mean()
print(result.compute())Two differences matter here.
- The pandas version reads every file into memory before any computation starts. The Dask version reads each file (or block of a file) as a separate partition, so it can process them one at a time or in parallel.
resultin the Dask version is a lazy object. The call to.compute()is what triggers the work and returns an ordinary pandas object. Chapters 4 and 5 explain this fully.
A decision guide
The question is not "is my data big?" but "what is limiting me?" The flowchart below sorts the common cases.
Try the cheap options first, because they cost nothing in complexity:
- Read only the columns you need with
usecols. - Use smaller dtypes, such as
categoryfor repeated strings andfloat32orint32where the range allows. - Read a CSV in pieces with the
chunksizeargument and combine partial results yourself. - Convert once to a columnar format such as Parquet, which is faster to load and lets you read only some columns.
If these are enough, you do not need Dask. If you find yourself writing a chunk loop with hand-written combine logic for every new aggregation, that is a sign Dask will save you effort.
When Dask is a good fit
Dask DataFrame works best in these situations:
- The data is stored as many files, or one large file that can be split into blocks, such as a folder of CSV or Parquet files.
- The workload is mostly filters, column assignments, and aggregations. These operate on each partition independently and then combine small partial results.
- The dataset is between a few gigabytes and a few terabytes, larger than comfortable memory on one machine.
- You want to use all cores on one machine, or grow to a cluster later without rewriting the analysis.
When Dask is the wrong tool
Dask adds overhead and some constraints. Avoid it, or expect trouble, in these cases:
- The data fits in memory and runs quickly. Building a task graph and scheduling tasks costs time. For small data, pandas is often faster.
- The operation needs all rows at once. Sorting, joining two large tables on a non-index column, and
groupbywith many distinct keys require moving data between partitions. This is called a shuffle, and it is the most expensive thing Dask does. Chapter 12 covers it. - You rely on row-order tricks. Operations such as
ilocby position, or logic that depends on one row following another across partition boundaries, are limited or missing. - You need the full pandas API. Dask implements a large subset. Some functions are absent or behave differently, and the documentation lists the gaps.
Adjacent tools
Dask is one of several answers to "pandas is not enough". The choice depends on your constraint.
| Tool | Approach | Typical reason to choose it |
|---|---|---|
| Dask DataFrame | Many pandas DataFrames, lazy task graph, pandas-like API | You want pandas semantics and a path from laptop to cluster |
| Polars | Multithreaded, columnar engine with its own API | The data fits on one machine and you want speed without a cluster |
| DuckDB | In-process SQL engine that can spill to disk | You prefer SQL and want to query large files on one machine |
| Spark | JVM-based distributed engine | You already operate a Spark cluster or need its ecosystem |
None of these is always best. If your team and code are built around pandas, Dask has the smallest learning curve. If you need only single-machine speed, Polars or DuckDB may suit you better than a parallel pandas.
How to check that you really need it
Measure before you move. Three quick checks give you evidence:
- Look at
pdf.memory_usage(deep=True).sum()for a sample, then scale up to the full row count. This gives a better estimate than the file size on disk. - Watch CPU use while your pandas job runs. One core at 100 percent and the rest idle suggests a compute limit that parallelism could help.
- Time the pandas version on a 5 to 10 percent sample. If the sample is fast, a full run may only need more memory and not a new library.
Summary of the model
Dask DataFrame gives you pandas-style code over partitioned data, evaluated lazily and run in parallel by a scheduler. It addresses memory limits and single-core limits, at the cost of overhead, a partial API, and expensive operations that move data between partitions. The rest of this tutorial builds that model one piece at a time, starting with partitions.
Exercise
Your pandas script loads a 2 GB CSV on a 32 GB machine and takes 25 minutes. CPU monitoring shows one core at 100 percent and the others idle. The work is a filter followed by a groupby mean. Is memory or compute the limit, and would you move to Dask straight away? Give one cheaper step to try first.
Show answer
Compute is the limit, not memory, because the data fits easily in RAM. The work is a filter and a groupby aggregation, which split well across partitions, so Dask could use the idle cores. Before moving, try a cheaper step such as reading only the needed columns with usecols, using smaller dtypes like category, or converting the CSV to Parquet once. Also time the script on a small sample to find where the 25 minutes go. If the time is spent in per-row Python work, Dask can help. If most of it is slow CSV parsing, a format change may fix it.
Exercise
Name two kinds of operations where Dask is a poor fit, and say why.
Show answer
Operations that need all rows together, such as a global sort or a join of two large tables on a non-index column, are costly because they force a shuffle that moves data between partitions. Operations that depend on row position or row order across partition boundaries, such as iloc by position, are also limited because Dask does not know the global row positions without extra work. Small datasets are a third poor fit, because task graph overhead exceeds any gain.