Sub topic 11
Loading less data: usecols, dtype, and Parquet
This chapter assumes you know basic Python, can work with pandas DataFrames (selecting columns, filtering, groupby), and understand NumPy dtypes at a basic level. It also assumes you have read the earlier chapters on timing and on dtypes and memory.
The fastest data to process is data you never load. Many slow pandas scripts spend most of their time in read_csv, parsing text into columns the script later ignores. This chapter shows how to read only what you need, store it in a better format, and check that the savings are real.
Why reading is often the bottleneck
A CSV file is text. To build a DataFrame, pandas must do the following:
- Split every line into fields.
- Guess the type of each column by scanning its values.
- Convert each text field to a number, date, or string object.
- Allocate memory for the result.
Each step scales with the number of columns and rows in the file. If you need 3 of 40 columns, you pay for all 40 unless you say otherwise. Profile first (see the earlier chapter on cProfile). If read_csv dominates, the techniques below pay off. If it takes 2% of the run time, skip them.
Reading only the columns you need with usecols
Pass usecols with a list of column names. pandas still reads the file from disk, but it does not convert the skipped columns into Python objects or arrays.
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
)
print(df.shape)Points to know:
usecolsaccepts names or integer positions. Names are safer, because a reordered file still works.- The order of columns in the result follows the file, not your list. Select with
df[["amount", "region"]]if order matters. - A name that is not in the file raises a
ValueError. That is useful, since it catches schema changes early. - Use
nrows=1000while developing. It reads only the first 1000 rows, which makes experiments fast. Remove it before the final run.
Choosing dtypes while reading
Without a dtype argument, pandas infers types. Integers become int64, decimals become float64, and text becomes object, which is a column of Python string objects. These defaults are safe but large.
Setting dtype at read time has two benefits. It skips inference, and it never creates the large intermediate columns that you would shrink afterward.
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
dtype={"region": "category", "amount": "float32"},
)
print(df.dtypes)
print(df.memory_usage(deep=True))Here region is a low-cardinality column (few distinct values repeated many times), so category stores each distinct string once plus a small integer code per row. float32 uses 4 bytes per value instead of 8.
Choosing safe compact types
| Column content | Default | Compact choice | Caution |
|---|---|---|---|
| Few distinct strings | `object` | `category` | Little gain if almost every value is unique |
| Whole numbers, small range | `int64` | `int32`, `int16`, `int8` | Values outside the range overflow or raise an error |
| Whole numbers with blanks | `float64` | `Int32` (nullable) | Capital `I` is the nullable type that allows missing values |
| Decimals | `float64` | `float32` | About 7 significant digits. Do not use for money totals |
| Text | `object` | `string[pyarrow]` | Needs pyarrow installed |
| Dates | `object` | use `parse_dates` | See below |
A common trap is float32 for currency. Summing 500,000 float32 values accumulates rounding error that float64 would not show. For exact money, store integer cents or use a decimal type. Compact types are for columns where a small error is acceptable.
Dates
Passing dtype={"created": "datetime64[ns]"} does not work in read_csv. Use parse_dates instead:
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "created", "amount"],
parse_dates=["created"],
dtype={"order_id": "int32", "amount": "float32"},
)
print(df.dtypes)If your date format is fixed, give pandas the format (for example date_format="%Y-%m-%d" in pandas 2.x). A known format avoids slow per-value guessing.
What happens when a dtype is wrong
If a column declared int32 contains a blank or the text "N/A", read_csv raises a ValueError. Treat that error as information about your data. Your options are to use a nullable type such as Int32, to list the markers in na_values, or to read the column as str and clean it first.
Measuring the benefit
Do not assume the options help. Time both versions with perf_counter, as in the timing chapter, and compare memory.
import pandas as pd
from time import perf_counter
start = perf_counter()
full = pd.read_csv("orders.csv")
t_full = perf_counter() - start
start = perf_counter()
slim = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
dtype={"region": "category", "amount": "float32"},
)
t_slim = perf_counter() - start
print(f"full: {t_full:.2f}s, {full.memory_usage(deep=True).sum() / 1e6:.1f} MB")
print(f"slim: {t_slim:.2f}s, {slim.memory_usage(deep=True).sum() / 1e6:.1f} MB")Run each read more than once. The operating system caches recently read files, so the first run is often slower than later ones.
Parquet: a better format for repeated work
If you read the same data many times, parsing text each time is wasted effort. Parquet is a columnar binary file format. It stores each column separately, along with its type, and compresses it.
This gives you three advantages over CSV:
- Types are stored. Reading back gives the same dtypes, including
categoryin most cases, with no inference. - Column pruning. Reading two columns touches only those two columns on disk.
- Compression. Files are usually several times smaller than the equivalent CSV.
Writing and reading needs pyarrow or fastparquet. Install one with pip install pyarrow.
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
dtype={"region": "category", "amount": "float32"},
)
df.to_parquet("orders.parquet")
subset = pd.read_parquet("orders.parquet", columns=["region", "amount"])
print(subset.dtypes)The pattern is to pay the CSV parsing cost once, save the result as Parquet, and read the Parquet file in every later run.
Filtering rows at read time
With the pyarrow engine, read_parquet accepts filters. Row groups (blocks of rows inside the file) whose stored minimum and maximum values rule out a match are skipped entirely.
import pandas as pd
north = pd.read_parquet(
"orders.parquet",
columns=["region", "amount"],
filters=[("region", "==", "N")],
)How much you save depends on how the data is laid out. If every row group contains every region, nothing can be skipped. Sorting by the filter column before writing makes row-group skipping effective.
Parquet limitations
- It is not human-readable. You cannot open it in a text editor.
- Writing is slower than writing CSV, and appending to an existing file is not supported by
to_parquet. Write a new file per batch instead. - Column names must be strings.
objectcolumns with mixed types (numbers and text) fail to write. Clean them first.- Different pyarrow and pandas versions can differ in how they round-trip some types. Test your own data.
Reading large files in pieces
If a file does not fit in memory, chunksize returns an iterator of DataFrames. Process each piece, keep only a small result, and combine at the end.
import pandas as pd
totals = []
for chunk in pd.read_csv(
"orders.csv",
usecols=["region", "amount"],
dtype={"region": "category", "amount": "float64"},
chunksize=100_000,
):
totals.append(chunk.groupby("region", observed=True)["amount"].sum())
result = pd.concat(totals).groupby(level=0).sum()
print(result)Notice that the loop appends small Series to a list and concatenates once, which follows the earlier advice on building frames. Chunking works for aggregations that can be combined, such as sums and counts. It does not work directly for operations that need all rows at once, such as a median or a global sort.
Each chunk infers category categories independently unless you declare them. Declaring a fixed list with pd.CategoricalDtype(["N", "S"]) keeps the categories consistent.
Choosing an approach
| Situation | Best first move |
|---|---|
| Script reads a wide CSV once and uses few columns | `usecols` and `dtype` |
| Same data is read many times | Convert once to Parquet |
| Queries select a subset of columns or rows | Parquet with `columns` and `filters` |
| File is larger than memory | `chunksize`, or a different tool (see the final chapter) |
| Data arrives as CSV and must stay CSV | `usecols`, `dtype`, `parse_dates` with format |
Common mistakes
- Declaring
int8orfloat32without checking the value range or precision needs. - Using
usecolsand then forgetting a column that a later step needs, which raises aKeyErrorfar from the cause. - Converting to
categoryfor a column with nearly unique values, which can use more memory thanobject. - Benchmarking only once and trusting a cached read.
- Assuming Parquet always speeds up the whole script. If the slow part is a row loop, the read format will not help.
Exercise
A script reads a 30-column CSV and uses only customer_id (unique integers up to 2 million), country (about 40 distinct values), and total (money amounts). It runs the same read every night. Name the read settings you would choose for each column, and say what you would change to speed up the later runs.
Show answer
Use usecols=["customer_id", "country", "total"]. Set customer_id to int32 (2 million fits within the int32 limit of about 2.1 billion), country to category (few distinct values repeated often), and keep total as float64 or store integer cents, because float32 loses precision on money. For later runs, write the cleaned frame to Parquet once with to_parquet, then use pd.read_parquet("file.parquet", columns=[...]) each night so no text parsing or type inference is repeated.
Exercise
Why can read_csv with dtype={"qty": "int8"} fail, and what are two ways to handle it?
Show answer
It fails if any value is outside the int8 range (-128 to 127) or if the column holds blanks or text such as "N/A", which cannot be stored in a plain integer type. Two fixes are to use a nullable type such as Int16 and list missing markers in na_values, or to read the column as str, clean it with pd.to_numeric(..., errors="coerce"), and then convert it to a suitable type.