Sub topic 3
Creating Dask DataFrames from files and from pandas
This chapter covers the ways to get a Dask DataFrame: from an in-memory pandas DataFrame, from CSV and Parquet files, and from other Dask objects. It assumes you know basic Python and pandas (selecting, filtering, assign, groupby) and that you have seen a Dask DataFrame described as a set of partitions. It also assumes you have installed dask[dataframe], which pulls in pandas and the pyarrow library used for Parquet.
What "creating" a Dask DataFrame means
Creating a Dask DataFrame does not load all the data. Dask records where each partition comes from and what the columns and dtypes should be. A partition is one ordinary pandas DataFrame, and a Dask DataFrame is an ordered collection of them.
Each constructor answers two questions:
- Where does each partition come from? It may be a slice of an object already in memory, a block of a file, or a whole file.
- What are the column names and dtypes? Dask needs these without reading everything. This description is called metadata, and a later chapter covers it in detail. For now, know that Dask builds it by sampling the data or by reading file headers.
From a pandas DataFrame
dd.from_pandas splits an existing pandas DataFrame into partitions. It is the quickest way to experiment, and it is useful in tests.
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) # 2
print(ddf) # shows column names and dtypes, not dataThe printed object shows the columns, their dtypes, and the number of partitions. It does not show rows, because Dask has not materialized a view of the data. To see a few rows, call ddf.head(), which computes only the first partition.
A few points about from_pandas:
- The data must already fit in memory, since you built the pandas DataFrame first. Use it for small data, tests and examples. For large data, read from files.
- You choose the split with
npartitionsor withchunksize(rows per partition). Pass one of them, not both. - Dask splits along the index. If the index is sorted, Dask records the boundary values between partitions. These are called divisions, and they let later operations such as
locand joins skip partitions. If the index is not sorted,from_pandassorts the data by index by default (sort=True). Passsort=Falseto keep the row order, but then Dask has no known divisions. - Dask may produce fewer partitions than you asked for if the data is too small or the index has too many repeated values to split cleanly.
From CSV files
dd.read_csv is the most direct replacement for pd.read_csv on large inputs. It accepts a path, a glob pattern, or a list of paths.
import dask.dataframe as dd
# One file, split into blocks of about 64 MB
ddf = dd.read_csv("data/trips-2024-01.csv", blocksize="64MB")
# Many files: by default, each file becomes at least one partition
ddf = dd.read_csv("data/trips-*.csv")Two things set the partition layout:
- With a glob, Dask makes at least one partition per file. A large file is also cut into blocks by
blocksize. blocksizesets the target bytes of raw text per partition. Dask cuts at byte offsets and then moves to the next newline, so a row is never split in two. Compressed files such as.csv.gzcannot be cut at arbitrary offsets, so passblocksize=Noneand each file becomes one partition.
Dtype inference is the common source of errors
When pandas reads a CSV, it sees the whole file and picks one dtype for each column. Dask reads each partition on its own. For the metadata, it samples only the start of the first file (the sample argument, 256 KB by default). If a column looks like integers in the sample but contains missing values or text later, a later partition fails with an error such as ValueError: Mismatched dtypes found in pd.read_csv/pd.read_table or a cast error during compute().
The fix is to state dtypes yourself.
import dask.dataframe as dd
ddf = dd.read_csv(
"data/trips-*.csv",
dtype={
"zone_id": "string", # IDs are labels, not numbers
"passenger_count": "float64", # contains missing values
},
parse_dates=["pickup_time"],
usecols=["zone_id", "passenger_count", "pickup_time", "fare"],
)Useful options, all of which follow pd.read_csv:
| Option | Purpose |
|---|---|
| `dtype` | Fix dtypes per column so all partitions agree |
| `parse_dates` | Parse listed columns as datetimes |
| `usecols` | Read only these columns, which saves memory and time |
| `blocksize` | Target size of each partition in bytes of text |
| `include_path_column` | Add a column with the source file path |
| `sample` | Bytes to read to guess dtypes |
Missing values are the usual reason an integer column fails. A pandas int64 column cannot hold NaN, so declare it float64, or use a nullable type such as "Int64".
Adding the file name
A common need is to know which file each row came from, for example when each file is one month. Use include_path_column:
import dask.dataframe as dd
ddf = dd.read_csv("data/trips-*.csv", include_path_column="source_file")
print(ddf.columns)The new column holds the path as a string, and you can parse it later to extract a date.
From Parquet files
Parquet is a columnar binary format. It stores the schema (names and dtypes) inside the file, so Dask does not need to guess. For this reason, Parquet is the recommended storage format for Dask work. A later chapter covers it fully. Here is the basic form of reading.
import dask.dataframe as dd
ddf.to_parquet("out/fares.parquet")
subset = dd.read_parquet("out/fares.parquet", columns=["zone", "fare"])
print(subset.npartitions)Points to know when you create a DataFrame this way:
read_parquetaccepts a directory, a single file, a glob, or a list of files. A directory written byto_parquetcontains one file per partition plus metadata files.columns=[...]reads only the listed columns from disk, because the format is columnar. Unlike CSV, unused columns cost nothing.- Dtypes come from the file schema, so you rarely get the mismatched dtype errors that CSV produces.
- The number of partitions follows the file layout. Many tiny files give many tiny partitions, which has its own costs (see the chapter on partition sizing).
From other sources and from Dask itself
Other constructors exist for less common cases. You will meet them as needed.
dd.from_dictanddd.from_arraybuild a DataFrame from dictionaries and arrays, with the samenpartitionsoption asfrom_pandas.dd.from_delayedbuilds a DataFrame from a list ofdask.delayedobjects that each return a pandas DataFrame. It is useful when your data comes from a custom loader, such as an API or a database query per partition. The last chapter showsdask.delayed.dd.read_json,dd.read_sql_tableanddd.read_orcread other formats.- Remote storage works with the same functions. Paths such as
s3://bucket/path/*.parquetneed the matching filesystem package (for examples3fs) and credentials, which you can pass withstorage_options={...}.
Inspecting what you created
After creating a DataFrame, check it before building a long analysis. These inspections are cheap because they do not read all the data.
import dask.dataframe as dd
ddf = dd.read_parquet("out/fares.parquet")
print(ddf.npartitions) # how many pandas DataFrames
print(ddf.dtypes) # column dtypes from the metadata
print(ddf.columns) # column names
print(ddf.divisions) # index boundaries, or (None, None, ...) if unknown
print(ddf.head()) # computes only the first partitionSome operations are not cheap. len(ddf) has to read every partition to count rows, so it triggers a full computation. ddf.shape returns a lazy value for the row count, so call .compute() on that first element only when you need it.
head() reads from the first partition only. If that partition has fewer rows than you asked for, you get fewer rows, and Dask may warn. Pass npartitions=-1 to search all partitions.
Choosing a source: decision guide
| Situation | Constructor |
|---|---|
| Small data, testing, examples | `from_pandas` |
| Raw CSV exports you do not control | `read_csv` with explicit `dtype` |
| Data you will read many times | Convert once to Parquet, then `read_parquet` |
| Custom loader or API | `from_delayed` |
A good habit is to read CSV once, fix the dtypes, write Parquet, and read that from then on. This keeps the slow, error-prone parsing out of the main analysis.
Common errors when creating DataFrames
- Dtype mismatch at compute time. Cause: inference from a sample. Fix: pass
dtype, or use Parquet. - One huge partition. Cause: reading a compressed CSV with
blocksize=None, or one big file. Fix: split the file before compression, or convert to Parquet. - Thousands of tiny partitions. Cause: many small input files. Fix: repartition after reading (a later chapter).
- Unexpected row order from
from_pandas. Cause: the default sort by index. Fix:sort=False, with the trade-off that divisions are unknown. - Slow
from_pandason big input. Cause: the whole pandas DataFrame was loaded first. Fix: read from files instead.
Exercise
You call dd.read_csv("logs/day-*.csv") on 30 files. The call returns instantly, but ddf["status"].sum().compute() fails on the 17th file with a dtype error, because status is an integer column that has blank values in that file. Give two ways to prevent this.
Show answer
First, pass dtype={"status": "float64"} (or the nullable "Int64") to read_csv, so every partition uses the same dtype even when blanks appear. Second, convert the CSVs to Parquet once with explicit dtypes and read the Parquet files instead, since the schema is stored in the files and no guessing is needed. The error appeared late because Dask inferred dtypes from a sample of only the first file and parsed the other files lazily at compute time.
Exercise
What is the difference between dd.from_pandas(pdf, npartitions=4) and dd.read_parquet("data/") in where the data lives when the DataFrame is created?
Show answer
With from_pandas, the full data is already in memory in the pandas DataFrame, and Dask only slices it into partitions. With read_parquet, nothing is loaded at creation. Dask reads the file metadata, and the partitions are read from disk only when you compute a result.