0Pricing
Pandas & NumPy Academy · Leçon

Introduction aux DataFrames Dask

Remplacez pd.read_csv et pd.DataFrame par leurs équivalents Dask, appelez compute() pour déclencher l’exécution et profilez les graphes de tâches.

Introduction aux DataFrames Dask est une leçon Pandas & NumPy Academy gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Pandas & NumPy Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Pandas & NumPy Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Questions Fréquemment Posées

La leçon « Introduction aux DataFrames Dask » est-elle gratuite ?

Oui — le texte complet de « Introduction aux DataFrames Dask » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Pandas & NumPy Academy, passe à CoddyKit PRO. Le cours Pandas & NumPy Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Introduction aux DataFrames Dask » ?

Remplacez pd.read_csv et pd.DataFrame par leurs équivalents Dask, appelez compute() pour déclencher l’exécution et profilez les graphes de tâches. Tu pratiques Pandas & NumPy Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Pandas & NumPy Academy ?

Aucune expérience préalable n'est requise. Pandas & NumPy Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « Introduction aux DataFrames Dask » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Pandas & NumPy Academy ?

Oui. Chaque leçon Pandas & NumPy Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Lire un CSV par flux avec chunksize
  2. Agrégation progressive entre les blocs
  3. Introduction aux DataFrames Dask
  4. Parquet : stockage colonnaire rapide
← Retour à Pandas & NumPy Academy