Sub topic 5
Reading less: usecols and dtype
This chapter assumes you know basic Python, pandas DataFrames, and read_csv. It also assumes you have read the chapters on measuring memory and reading in chunks. Chunking limits how many rows are in memory at once. usecols and dtype shrink each row, so the two techniques work together.
Why read less
By default, read_csv loads every column and guesses a type for each one. Text columns become object, which stores a full Python string per cell. Integers become int64 and decimals become float64, even when the values are small. Both defaults are expensive on a large file.
The cheapest data is data you never load. Choose columns first, then choose compact types for the columns you keep.
Selecting columns with usecols
usecols tells the parser which columns to keep. The other columns are skipped while parsing, so they never take up memory in the DataFrame.
import pandas as pd
sample = pd.read_csv("sales.csv", nrows=100_000)
print(sample.memory_usage(deep=True).sum() / 1024**2, "MiB")
slim = pd.read_csv(
"sales.csv",
nrows=100_000,
usecols=["region", "amount", "order_date"],
)
print(slim.memory_usage(deep=True).sum() / 1024**2, "MiB")You can pass column names or integer positions. Names are easier to read and survive a column being reordered. The order in usecols does not change the order of the result. Columns always appear in file order.
Choosing smaller dtypes
The dtype parameter maps column names to types. Three changes cover most cases.
| Column content | Default | Better choice |
|---|---|---|
| Repeated labels, such as region or status | `object` | `category` |
| Small whole numbers | `int64` | `int32`, `int16`, or `int8` |
| Decimals that need less precision | `float64` | `float32` |
A category column stores each distinct label once and keeps a small integer code per row. It saves the most when a column has few distinct values compared with its row count.
import pandas as pd
dtypes = {
"region": "category",
"store_id": "int32",
"amount": "float32",
}
sample = pd.read_csv(
"sales.csv",
nrows=100_000,
usecols=["region", "store_id", "amount"],
dtype=dtypes,
)
print(sample.memory_usage(deep=True).sum() / 1024**2, "MiB")
print(sample.dtypes)Dates are the exception. Do not put them in dtype. Use parse_dates=["order_date"] so pandas converts them to datetime64.
Combining both with chunks
Pass the same arguments to the chunked reader. Every chunk then uses the slim layout.
import pandas as pd
dtypes = {"region": "category", "store_id": "int32", "amount": "float32"}
totals = None
with pd.read_csv(
"sales.csv",
usecols=["region", "amount"],
dtype={"region": "category", "amount": "float32"},
chunksize=200_000,
) as reader:
for chunk in reader:
part = chunk.groupby("region", observed=True)["amount"].sum()
totals = part if totals is None else totals.add(part, fill_value=0)
print(totals)Because the types are fixed up front, every chunk gets the same dtypes. Without them, pandas infers types separately for each chunk, and the types can differ.
Common errors
- Conversion failure. If a column declared
int32contains a blank or text value,read_csvraises aValueError. Use a float type or the nullable"Int32"for columns with missing values. - Overflow.
int8holds only -128 to 127. Check the real minimum and maximum before you shrink a column. Reading a sample and callingdescribe()is usually enough, but a rare large value later in the file can still break the load. - Precision loss.
float32keeps about seven significant digits. Do not use it for money totals that must be exact. Sums over millions of rows also accumulate more rounding error. - A misspelled name in usecols. pandas raises a
ValueErrorbecause the column does not exist. Printsample.columnsfirst. - Per-chunk categories. Each chunk's
categorycolumn may hold a different set of labels, and combining chunks can silently turn them back intoobject. Declare a fixed type withpd.CategoricalDtype(categories=[...])when you know the labels.
Exercise
A column named status holds only the values "ok", "error", and "retry" across 50 million rows. A column named count holds whole numbers from 0 to 90. How would you declare these in dtype, and why is each choice safe?
Show answer
Use dtype={"status": "category", "count": "int8"}. Status has three distinct labels, so a category stores each label once and a small code per row instead of a string per row. The count values fit in int8 (-128 to 127). Both are safe only if the full file has no missing or out-of-range values. If blanks are possible, use "Int8" for count instead.