Introduction to Dask DataFrames
Replace pd.read_csv and pd.DataFrame with dask equivalents, call compute() to trigger execution, and profile task graphs.
Introduction to Dask DataFrames is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Dask?
Dask is a parallel computing library for Python that extends NumPy and Pandas to datasets larger than RAM. Its dask.dataframe module provides a DataFrame API almost identical to Pandas, but instead of executing operations immediately, Dask builds a task graph and executes it lazily when you call .compute(). This allows Dask to parallelise work across multiple cores or even multiple machines with minimal code changes.
Installing and Importing Dask
Dask is installed with pip install dask[dataframe]. The import convention is import dask.dataframe as dd. Under the hood, a Dask DataFrame is partitioned into many smaller Pandas DataFrames, each processed independently. Operations on the Dask DataFrame create a lazy task graph — nothing runs until .compute() is called. This separation between describing and executing computation is the key insight of Dask.
import dask.dataframe as dd
# Read a large CSV — returns a Dask DataFrame immediately (no data loaded yet)
ddf = dd.read_csv('large_sales.csv')
print(type(ddf)) # dask.dataframe.core.DataFrame
print(ddf.columns.tolist())
print(ddf.dtypes)Dask vs Pandas: The Key Difference
With Pandas, every operation executes immediately and eagerly. With Dask, operations return another Dask object representing the deferred computation. Only when you call .compute() does Dask actually read data and execute the task graph. This laziness allows Dask to optimise the plan before executing — for example, it can fuse consecutive filters to avoid loading data multiple times. Think of it like a recipe: Dask writes the recipe; .compute() cooks the meal.
import dask.dataframe as dd
ddf = dd.read_csv('sales.csv')
# This does NOT run yet — just builds the task graph
filtered = ddf[ddf['amount'] > 1000]
agg = filtered.groupby('region')['amount'].sum()
print(type(agg)) # dask.dataframe.core.Series
# NOW execute everything
result = agg.compute()
print(result)Partitions: The Core Concept
A Dask DataFrame is split into partitions, each of which is a regular Pandas DataFrame. By default, dd.read_csv creates one partition per file (or one per 128 MB for large files). You can control this with blocksize. Checking ddf.npartitions shows how many partitions exist. More partitions enable more parallelism but add overhead; fewer partitions reduce overhead but limit parallelism. The sweet spot is typically a few hundred partitions.
import dask.dataframe as dd
ddf = dd.read_csv('data/*.csv') # Read multiple CSV files at once
print('Number of partitions:', ddf.npartitions)
# Access a single partition as a Pandas DataFrame
first_partition = ddf.get_partition(0).compute()
print('Partition 0 shape:', first_partition.shape)Familiar Pandas Operations in Dask
Most common Pandas operations work identically in Dask: .head(), .tail(), .describe(), boolean indexing, .groupby(), .merge(), and .assign() all have Dask equivalents. The biggest difference is that you must call .compute() to materialise the result. Operations that Pandas handles in milliseconds may take seconds in Dask due to task graph overhead — so use Pandas for small data and Dask when data does not fit in RAM.
import dask.dataframe as dd
ddf = dd.read_csv('transactions.csv')
# Filtering — same syntax as Pandas
high_value = ddf[ddf['amount'] > 500]
# GroupBy aggregation
by_region = high_value.groupby('region')['amount'].mean()
# Execute
result = by_region.compute()
print(result.sort_values(ascending=False))Reading Multiple Files with Glob Patterns
One of Dask's most useful features is reading multiple files at once using glob patterns. dd.read_csv('data/2024-*.csv') reads all matching files and creates one partition per file. This is perfect for data stored as monthly or daily partitioned files, a common pattern in data lakes. Dask aligns the schemas automatically, equivalent to manually looping and concatenating with Pandas but much simpler.
import dask.dataframe as dd
# Read all monthly files at once
ddf = dd.read_csv('sales/2024-*.csv',
dtype={'order_id': 'int32',
'amount': 'float32'})
print(f'Partitions: {ddf.npartitions}') # One per file
print(f'Total rows (lazy): {len(ddf)}') # This triggers a compute!The visualize() Method for Task Graphs
Before executing a complex Dask pipeline, you can inspect the task graph by calling result.visualize(), which generates a PNG diagram of all computation steps. This is valuable for understanding what Dask will execute and debugging unexpected slowness. The graph shows how partitions flow through filter, groupby, and aggregation steps, making it easy to spot redundant computations. Requires the graphviz package.
import dask.dataframe as dd
ddf = dd.read_csv('orders.csv')
pipeline = (
ddf[ddf['status'] == 'completed']
.groupby('product_id')['revenue']
.sum()
)
# Visualise the task graph (saves to PNG)
# pipeline.visualize('task_graph.png')
# Check number of tasks in the graph
print('Number of tasks:', len(pipeline.__dask_graph__()))Applying Custom Functions with map_partitions
When you need to apply a custom Pandas function to a Dask DataFrame, use ddf.map_partitions(func). This applies func to each partition independently and returns a new Dask DataFrame. The function receives a regular Pandas DataFrame and must return one. This is the Dask equivalent of df.apply() and is how you integrate Dask with code that only understands Pandas.
import dask.dataframe as dd
import pandas as pd
def normalise_chunk(df):
df = df.copy()
df['amount_norm'] = (df['amount'] - df['amount'].mean()) / df['amount'].std()
return df
ddf = dd.read_csv('data.csv')
normalised = ddf.map_partitions(normalise_chunk)
result = normalised[['order_id', 'amount_norm']].compute()
print(result.head())Dask Scheduler Options
Dask has multiple schedulers that control how tasks are executed. The 'synchronous' scheduler runs tasks sequentially in the current thread (useful for debugging). The 'threads' scheduler uses a thread pool (good for I/O-bound work). The 'processes' scheduler spawns multiple processes for CPU-bound work (bypasses Python's GIL). A Dask distributed cluster enables multi-machine execution. Specify the scheduler via compute(scheduler='threads').
import dask.dataframe as dd
ddf = dd.read_csv('data.csv')
agg = ddf.groupby('category')['sales'].sum()
# Choose scheduler based on workload
result_sync = agg.compute(scheduler='synchronous') # sequential, easy to debug
result_threads = agg.compute(scheduler='threads') # parallel I/O
result_processes = agg.compute(scheduler='processes') # parallel CPUConverting Between Dask and Pandas
It is common to process a large dataset with Dask and then bring the aggregated result into Pandas for the final analysis or visualisation. Use .compute() to convert a Dask DataFrame to Pandas. Going the other direction, dd.from_pandas(df, npartitions=4) converts a Pandas DataFrame to a Dask DataFrame, which is useful for testing Dask code on small data before scaling up to the full dataset.
import pandas as pd
import dask.dataframe as dd
# Start with a small Pandas DF for testing
df_small = pd.DataFrame({'a': range(100), 'b': range(100, 200)})
# Convert to Dask for development/testing
ddf = dd.from_pandas(df_small, npartitions=4)
result = ddf.groupby('a')['b'].sum().compute()
print(type(result)) # pandas.Series
print(result.head())When to Use Dask vs Pandas vs SQL
Dask is not always the right tool. Use Pandas when your data fits in RAM (less than a few GB) — it is simpler and faster due to less overhead. Use Dask when data exceeds RAM but you want Pandas-like syntax and single-machine parallelism. Use SQL/database when data lives in a relational database and aggregations can be pushed to the database engine. Use Spark or BigQuery when you need multi-machine distributed processing at petabyte scale.
Quick Check
Test your understanding of Data Analysis concepts from this lesson.
Lesson Recap
In this lesson you learned: Dask DataFrames are lazily evaluated collections of Pandas partitions with a familiar API, .compute() triggers actual execution of the task graph, and map_partitions lets you apply any custom Pandas function across all partitions. Next up we look at Parquet format as a fast, columnar alternative to CSV for storing large datasets.
Frequently asked questions
Is the “Introduction to Dask DataFrames” lesson free?
Yes — the full text of “Introduction to Dask DataFrames” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Introduction to Dask DataFrames”?
Replace pd.read_csv and pd.DataFrame with dask equivalents, call compute() to trigger execution, and profile task graphs. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Introduction to Dask DataFrames” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Streaming CSV with chunksize
- Incremental Aggregation Across Chunks
- Introduction to Dask DataFrames
- Parquet: Fast Columnar Storage