Sub topic 5
Reading less: usecols and dtype
This chapter assumes you can read a CSV with pd.read_csv, know what a DataFrame's dtypes are, and have seen chunksize iteration. Chunking limits how many rows you hold at once. usecols and dtype limit how much each row costs. Combined, they often decide whether a job fits in memory at all.
Why reading less matters
By default, read_csv parses every column and infers a dtype for each one. Inference is conservative. Integers become int64, decimals become float64, and anything it cannot classify becomes object, which stores one Python string per cell. For a typical file, three things waste memory:
- Columns you never use.
- Numeric columns stored at 64 bits when the values fit in 8, 16 or 32 bits.
- Text columns with few distinct values, stored as one string object per row.
The fix is to tell pandas, before it parses anything, which columns you need and what type each one should have. Memory that is never allocated cannot run out.
Selecting columns with usecols
usecols tells the parser to keep only the named columns. The other columns are skipped during parsing, so they never become part of the DataFrame.
import pandas as pd
df = pd.read_csv(
"sales.csv",
usecols=["region", "amount", "order_date"],
nrows=100_000,
)
print(df.columns.tolist())
print(df.memory_usage(deep=True).sum() / 1024**2, "MiB")You can pass names, as above, or integer positions such as usecols=[0, 3, 5]. Names are clearer and survive column reordering in the source file. Positions are useful when the file has no header or has duplicate names.
Two behaviors are worth knowing:
- The order of
usecolsdoes not control the order of the resulting columns. The DataFrame follows the file's column order. If you need a specific order, reindex afterward withdf = df[["amount", "region"]]. - A name that is not in the file raises a
ValueError. This is useful, because a renamed column in an upstream export fails loudly instead of silently dropping data.
usecols also accepts a callable that receives each column name and returns True to keep it:
import pandas as pd
df = pd.read_csv(
"sales.csv",
usecols=lambda name: not name.startswith("debug_"),
nrows=100_000,
)
print(df.columns.tolist())This is handy for wide files where it is easier to describe what to exclude.
Choosing dtypes with dtype
The dtype parameter maps column names to types. It replaces inference for those columns.
import pandas as pd
dtypes = {
"store_id": "int32",
"quantity": "int16",
"amount": "float32",
"region": "category",
}
df = pd.read_csv(
"sales.csv",
usecols=["store_id", "quantity", "amount", "region"],
dtype=dtypes,
nrows=100_000,
)
print(df.dtypes)
print(df.memory_usage(deep=True).sum() / 1024**2, "MiB")Each choice has a different effect, summarized below.
| Type | Bytes per value | Good for | Watch out for |
|---|---|---|---|
| `int64` (default) | 8 | Large IDs, counts | Wastes space for small values |
| `int32` | 4 | IDs up to about 2.1 billion | Overflow beyond that range |
| `int16` | 2 | Values from -32,768 to 32,767 | Overflow on larger values |
| `int8` | 1 | Flags, small codes | Range only -128 to 127 |
| `float32` | 4 | Measurements where about 7 significant digits are enough | Rounding in money and large sums |
| `category` | 1 to 4 per row, plus a lookup table | Text with few distinct values | Many distinct values gives little saving |
| `string` | Varies | Free text | Still stores the text itself |
Measuring the effect
Use the technique from the earlier measurement chapter. Read a sample twice, once with defaults and once with your choices, and compare:
import pandas as pd
cols = ["store_id", "quantity", "amount", "region"]
default = pd.read_csv("sales.csv", usecols=cols, nrows=100_000)
tuned = pd.read_csv(
"sales.csv",
usecols=cols,
nrows=100_000,
dtype={
"store_id": "int32",
"quantity": "int16",
"amount": "float32",
"region": "category",
},
)
before = default.memory_usage(deep=True).sum() / 1024**2
after = tuned.memory_usage(deep=True).sum() / 1024**2
print(f"default: {before:.1f} MiB, tuned: {after:.1f} MiB")The category column typically gives the biggest drop. A column of region names stored as object holds a separate string per row. As category, it holds a small integer code per row and one copy of each distinct name.
Overflow and precision: the risks of small types
Smaller types trade safety for space. Two risks matter.
First, integer overflow. If a column declared int8 contains 300, read_csv raises an error, and the failure happens when the offending chunk is parsed. That could be hours into a job. Check the real range of your data before choosing a type. A cheap way is to find min and max in a first pass that reads only that column:
import pandas as pd
lo, hi = None, None
with pd.read_csv("sales.csv", usecols=["quantity"], chunksize=200_000) as reader:
for chunk in reader:
c_lo, c_hi = chunk["quantity"].min(), chunk["quantity"].max()
lo = c_lo if lo is None else min(lo, c_lo)
hi = c_hi if hi is None else max(hi, c_hi)
print(lo, hi)
print(pd.api.types.is_integer_dtype("int16"), "int16 range:", (-32768, 32767))Second, precision. float32 holds about seven significant digits. Summing millions of float32 values can accumulate visible error, and currency values like 1234567.89 cannot be represented exactly. For money, keep float64, or store integer cents. A common rule: shrink integers freely once you have checked the range, and be conservative with floats.
Columns that cannot be integers
Integer dtypes cannot hold missing values in the classic NumPy form. If a column declared int32 has an empty cell, the read fails with an error about converting NaN to integer. You have two options:
- Use pandas nullable integers, written with a capital letter:
"Int32". They store missing values aspd.NA. - Read the column as
float64and convert later, once you have handled the missing values.
import pandas as pd
df = pd.read_csv(
"sales.csv",
usecols=["store_id", "quantity"],
dtype={"store_id": "Int32", "quantity": "Int16"},
nrows=100_000,
)
print(df.dtypes)
print(df.isna().sum())Dates are not set with dtype
Dates are a special case. Writing dtype={"order_date": "datetime64[ns]"} does not work in read_csv. Use parse_dates instead:
import pandas as pd
df = pd.read_csv(
"sales.csv",
usecols=["order_date", "amount"],
parse_dates=["order_date"],
nrows=100_000,
)
print(df.dtypes)Without parse_dates, the column is read as object strings, which is the most expensive form. Parsing dates costs CPU time, so do it only for columns you will use as dates.
Why dtype matters even more with chunks
Chunked reading has a failure mode that whole-file reads avoid. When pandas infers types, it infers them per chunk. A column that looks like integers in the first chunk can contain a blank or a text value in a later chunk, and its dtype changes from one chunk to the next. Then combining results can produce mixed types, or a category column with different categories in each chunk.
Declaring dtype explicitly makes every chunk use the same schema. This is the main reason to set it even when memory is not tight.
The diagram shows how the two options act at different points of the read.
Putting it together with chunks
The full pattern combines all three controls: a column list, a dtype map, and a chunk size. Here it computes the total amount per region.
import pandas as pd
dtypes = {
"region": "category",
"quantity": "int16",
"amount": "float64",
}
totals = None
with pd.read_csv(
"sales.csv",
usecols=list(dtypes),
dtype=dtypes,
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)Notes on this example:
usecols=list(dtypes)reuses the dictionary keys, so the two lists cannot drift apart.observed=Truemakesgroupbyreturn only categories that appear in the chunk. Without it, grouping on a categorical column can produce a row for every known category, including empty ones, which changes the result shape.- Each chunk is small because both the row count and the per-row cost are limited.
Common mistakes
- Passing a dtype for a column not in
usecols. pandas ignores it silently or may raise depending on the version. Keep the two in sync. - Choosing
categoryfor a column with nearly unique values, such as order IDs. The lookup table then costs as much as the strings it replaces. - Forgetting that
categorycodes are per chunk unless the categories are fixed. If you need identical categories in every chunk, declare them withpd.CategoricalDtype(categories=[...])and pass that object as the dtype. - Relying on inference for the first chunk and then assuming it holds for the rest.
- Setting
low_memory=Falseas a fix for mixed-type warnings. It forces whole-column inference and uses more memory. An explicitdtypeis the proper fix.
Exercise
A file has columns id (values up to 50 million), status (five distinct strings), score (whole numbers from 0 to 100, some cells empty) and notes (free text you do not need). Write the read_csv arguments usecols and dtype that minimize memory without losing data or raising errors.
Show answer
Use usecols=["id", "status", "score"] to skip notes. Use dtype={"id": "int32", "status": "category", "score": "Int8"}. int32 holds values up to about 2.1 billion, so 50 million fits. status has few distinct values, so category is compact. score fits in 8 bits, but the empty cells would break a plain int8, so the nullable Int8 (capital I) is needed, because it represents missing values as pd.NA.
Exercise
Why can leaving dtypes to inference cause problems in a chunked read even when memory is plentiful?
Show answer
pandas infers types separately for each chunk. A column that is all integers in one chunk may contain a blank or text in another, so its dtype changes between chunks. Partial results from different chunks then have mismatched types, and combining them can fail or give wrong results. An explicit dtype gives every chunk the same schema.