0Pricing
Pandas & NumPy Academy · 课时

Dask DataFrames 入门

使用 Dask 的对应功能替代 pd.read_csv 和 pd.DataFrame,调用 compute() 触发执行,并分析任务图的性能。

Dask DataFrames 入门 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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 CPU

Converting 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.

常见问题解答

「Dask DataFrames 入门」课时是免费的吗?

是的 — 「Dask DataFrames 入门」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。

「Dask DataFrames 入门」这节课中我会学到什么?

使用 Dask 的对应功能替代 pd.read_csv 和 pd.DataFrame,调用 compute() 触发执行,并分析任务图的性能。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Pandas & NumPy Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「Dask DataFrames 入门」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?

能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 chunksize 流式读取 CSV
  2. 跨数据块增量聚合
  3. Dask DataFrames 入门
  4. Parquet:高速列式存储
← 返回 Pandas & NumPy Academy