Sub topic 1
When pandas is not enough, and what Dask adds
Prerequisites
You should know basic Python, pandas DataFrames, filtering, groupby, and aggregation. You should also understand that one machine has finite memory.
When pandas is not enough, and what Dask adds
pandas keeps a DataFrame in one process's memory. This is simple and often fast, but it becomes a poor fit when the data does not fit in memory or one process takes too long to finish.
Dask is a Python library for parallel computing. Dask DataFrame provides a pandas-like interface while splitting the data into smaller pieces. Dask can process those pieces across several CPU cores or machines.
Dask does not make every operation faster. Small datasets often run faster in pandas because Dask adds scheduling overhead. Dask is most useful when the data or computation is large enough to benefit from partitioning.
Partitions: a DataFrame made of many pandas DataFrames
A partition is one smaller pandas DataFrame. A Dask DataFrame is a logical collection of these partitions.
Many operations can run independently on each partition. For example, filtering rows or adding a column usually requires no communication between partitions. Aggregations and joins can require data to move between partitions. This movement is called a shuffle and can be expensive.
Creating Dask DataFrames from files and from pandas
Use dd.read_csv("data/*.csv") or dd.read_parquet("data/") to create a Dask DataFrame from files. For a pandas DataFrame, use dd.from_pandas.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
print(ddf.npartitions)
print(ddf.dtypes)npartitions reports the number of pandas pieces. Choose it based on data size and available resources, rather than treating a larger number as automatically better.
Lazy evaluation and task graphs
Dask is lazy. A filter or aggregation usually creates a task graph, which is a description of future work. It does not immediately read and process every row.
Call .compute() to execute the graph and return an in-memory pandas result. Call .persist() when you want computed partitions to remain available for later operations.
mean_fare = ddf[ddf["fare"] > 15].groupby("zone")["fare"].mean()
result = mean_fare.compute()
print(result)A common error is inspecting a lazy object and assuming the calculation has already run. Check the final result with compute(), and remember that a result too large for memory should not be collected into one pandas object.
Exercise
Why can filtering be cheaper than a groupby in Dask?
Show answer
Filtering can run independently within each partition, while groupby may shuffle rows between partitions.