Alterlab dask

From AlterLab-IEU/AlterLab-Academic-Skills · View interactive version

Alterlab dask is an AI agent skill from the GitHub repository AlterLab-IEU/AlterLab-Academic-Skills. Scales pandas/NumPy workflows beyond memory with Dask distributed computing — parallel DataFrames, arrays, delayed task graphs, and cluster execution. Use when existing pandas/NumPy code must run on larger-than-RAM data or across clusters, for parallel file processing, distributed ML, or integration

How to use this skill

Skill file

Dask

Overview

Dask is a Python library for parallel and distributed computing that enables three critical capabilities:

Dask scales from laptops (processing ~100 GiB) to clusters (processing ~100 TiB) while maintaining familiar Python APIs.

When to Use This Skill

This skill should be used when:

Does NOT Trigger

| Scenario | Use Instead |

|----------|-------------|

| Data fits in RAM and the goal is maximum single-machine DataFrame speed | alterlab-polars |

| Billion-row out-of-core exploration and big-data plots on one machine, no cluster | alterlab-vaex |

| Designing chunked, compressed Zarr stores and codecs (rather than computing on them) | alterlab-zarr |

Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-polars) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.

Version notes

Since 2025.1 the query-planning DataFrame (formerly dask-expr) is the only Dask DataFrame

implementation and ships inside dask; dask.config.set({"dataframe.query-planning": False})

no longer exists. Text columns load as a string dtype (PyArrow-backed in Dask; str in pandas 3)

and reductions do not skip them silently: ddf.mean() raises TypeError and

ddf.groupby(...).mean() raises NotImplementedError when non-numeric columns are present, so

select columns or pass numeric_only=True.

Core Capabilities

Dask provides five main components, each suited to different use cases:

1. DataFrames - Parallel Pandas Operations

Purpose: Scale pandas operations to larger datasets through parallel processing.

When to Use:

Reference Documentation: For comprehensive guidance on Dask DataFrames, refer to references/dataframes.md which includes:

Quick Example:

import dask.dataframe as dd

# Read multiple files as single DataFrame
ddf = dd.read_csv('data/2024-*.csv')

# Operations are lazy until compute()
filtered = ddf[ddf['value'] > 100]
result = filtered.groupby('category').mean(numeric_only=True).compute()

Key Points:

2. Arrays - Parallel NumPy Operations

Purpose: Extend NumPy capabilities to datasets larger than memory using blocked algorithms.

When to Use:

Reference Documentation: For comprehensive guidance on Dask Arrays, refer to references/arrays.md which includes:

Quick Example:

import dask.array as da

# Create large array with chunks
x = da.random.random((100000, 100000), chunks=(10000, 10000))

# Operations are lazy
y = x + 100
z = y.mean(axis=0)

# Compute result
result = z.compute()

Key Points:

3. Bags - Parallel Processing of Unstructured Data

Purpose: Process unstructured or semi-structured data (text, JSON, logs) with functional operations.

When to Use:

Reference Documentation: For comprehensive guidance on Dask Bags, refer to references/bags.md which includes:

Quick Example:

import dask.bag as db
import json

# Read and parse JSON files
bag = db.read_text('logs/*.json').map(json.loads)

# Filter and transform
valid = bag.filter(lambda x: x['status'] == 'valid')
processed = valid.map(lambda x: {'id': x['id'], 'value': x['value']})

# Convert to DataFrame for analysis
ddf = processed.to_dataframe()

Key Points:

4. Futures - Task-Based Parallelization

Purpose: Build custom parallel workflows with fine-grained control over task execution and dependencies.

When to Use:

Reference Documentation: For comprehensive guidance on Dask Futures, refer to references/futures.md which includes:

Quick Example:

from dask.distributed import Client

client = Client()  # Create local cluster

# Submit tasks (executes immediately)
def process(x):
    return x ** 2

futures = client.map(process, range(100))

# Gather results
results = client.gather(futures)

client.close()

Key Points:

5. Schedulers - Execution Backends

Purpose: Control how and where Dask tasks execute (threads, processes, distributed).

When to Choose Scheduler:

Reference Documentation: For comprehensive guidance on Dask Schedulers, refer to references/schedulers.md which includes:

Quick Example:

import dask
import dask.dataframe as dd

# Use threads for DataFrame (default, good for numeric)
ddf = dd.read_csv('data.csv')
result1 = ddf.mean(numeric_only=True).compute()  # Uses threads

# Use processes for Python-heavy work
import dask.bag as db
bag = db.read_text('logs/*.txt')
result2 = bag.map(python_function).compute(scheduler='processes')

# Use synchronous for debugging
dask.config.set(scheduler='synchronous')
result3 = problematic_computation.compute()  # Can use pdb

# Use distributed for monitoring and scaling
from dask.distributed import Client
client = Client()
result4 = computation.compute()  # Uses distributed with dashboard

Key Points:

Best Practices

For comprehensive performance optimization guidance, memory management strategies, and common pitfalls to avoid, refer to references/best-practices.md. Key principles include:

Start with Simpler Solutions

Before using Dask, explore:

Critical Performance Rules

1. Don't Load Data Locally Then Hand to Dask

# Wrong: Loads all data in memory first
import pandas as pd
df = pd.read_csv('large.csv')
ddf = dd.from_pandas(df, npartitions=10)

# Correct: Let Dask handle loading
import dask.dataframe as dd
ddf = dd.read_csv('large.csv')

2. Avoid Repeated compute() Calls

# Wrong: Each compute is separate
for item in items:
    result = dask_computation(item).compute()

# Correct: Single compute for all
computations = [dask_computation(item) for item in items]
results = dask.compute(*computations)

3. Don't Build Excessively Large Task Graphs

4. Choose Appropriate Chunk Sizes

5. Use the Dashboard

from dask.distributed import Client
client = Client()
print(client.dashboard_link)  # Monitor performance, identify bottlenecks

Common Workflow Patterns

ETL Pipeline

import dask.dataframe as dd

# Extract: Read data
ddf = dd.read_csv('raw_data/*.csv')

# Transform: Clean and process
ddf = ddf[ddf['status'] == 'valid']
ddf['amount'] = ddf['amount'].astype('float64')
ddf = ddf.dropna(subset=['important_col'])

# Load: Aggregate and save. Named aggregation keeps flat string column names;
# a dict-of-lists .agg() creates MultiIndex columns that Parquet rejects.
summary = ddf.groupby('category').agg(
    amount_sum=('amount', 'sum'),
    amount_mean=('amount', 'mean'),
)
summary.to_parquet('output/summary.parquet')

Unstructured to Structured Pipeline

import dask.bag as db
import json

# Start with Bag for unstructured data
bag = db.read_text('logs/*.json').map(json.loads)
bag = bag.filter(lambda x: x['status'] == 'valid')

# Convert to DataFrame for structured analysis
ddf = bag.to_dataframe()
result = ddf.groupby('category').mean(numeric_only=True).compute()

Large-Scale Array Computation

import dask
import dask.array as da

# Load or create large array
x = da.from_zarr('large_dataset.zarr')

# Pass 1: global statistics in one read (float64 accumulators for float32 data)
mean, std = dask.compute(x.mean(dtype='float64'), x.std(dtype='float64'))

# Pass 2: elementwise, chunk by chunk; each output chunk needs only its own input chunk
normalized = ((x - mean) / std).astype(x.dtype)
da.to_zarr(normalized, 'normalized.zarr')

For data larger than memory, do not write the lazy one-liner (x - x.mean()) / x.std(): every output chunk then waits on a full-array reduction, so the scheduler keeps the loaded input chunks in memory until it finishes (with dask 2026.8 a 128 MB Zarr array peaked at ~133 MB that way and ~7 MB in two passes).

Custom Parallel Workflow

from dask.distributed import Client

client = Client()

# Scatter large dataset once
data = client.scatter(large_dataset)

# Process in parallel with dependencies
futures = []
for param in parameters:
    future = client.submit(process, data, param)
    futures.append(future)

# Gather results
results = client.gather(futures)

Selecting the Right Component

Use this decision guide to choose the appropriate Dask component:

Data Type:

Operation Type:

Control Level:

Workflow Type:

Integration Considerations

File Formats

Conversion Between Collections

# Bag → DataFrame
ddf = bag.to_dataframe()

# DataFrame → Array (for numeric data)
arr = ddf.to_dask_array(lengths=True)

# Array → DataFrame
ddf = dd.from_dask_array(arr, columns=['col1', 'col2'])

With Other Libraries

Debugging and Development

Iterative Development Workflow

  1. Test on small data with synchronous scheduler:
dask.config.set(scheduler='synchronous')
result = computation.compute()  # Can use pdb, easy debugging
  1. Validate with threads on sample:
sample = ddf.head(1000)  # Small sample
# Test logic, then scale to full dataset
  1. Scale with distributed for monitoring:
from dask.distributed import Client
client = Client()
print(client.dashboard_link)  # Monitor performance
result = computation.compute()

Common Issues

Memory Errors:

Slow Start:

Poor Parallelization:

Reference Files

All reference documentation files can be read as needed for detailed information:

Load these files when users need detailed information about specific Dask components, operations, or patterns beyond the quick guidance provided here.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.