Sub topic 10
Setting dtypes and columns when reading files
This chapter assumes you know how DataFrame columns carry dtypes, why object columns cost more memory than fixed-width ones, and how category and downcasting save space. Here you apply those ideas at load time, so the large default-typed frame is never built.
Why load-time choices matter
By default, read_csv guesses a dtype for every column. It gives integers int64, decimals float64, and text object. A file with a few narrow columns then takes much more memory than it needs. If you convert afterward with astype, you pay for the large frame first and then for the smaller one.
Two arguments avoid that:
usecolsloads only the columns you name. Skipped columns are never stored.dtypesets the dtype of each column as it is parsed.
A worked example
The next block reads a small in-memory CSV. It keeps all three columns and sets a compact dtype for each.
import io
import pandas as pd
csv = io.StringIO("id,city,score\n1,Oslo,0.5\n2,Lima,0.7\n3,Oslo,0.9\n")
df = pd.read_csv(
csv,
usecols=["id", "city", "score"],
dtype={"id": "int32", "city": "category", "score": "float32"},
)
print(df.dtypes)The output shows id as int32, city as category, and score as float32. The city column stores each distinct name once and keeps a small integer code per row.
Choosing a dtype for each column
Pick the dtype from what you know about the data, not from a guess.
| Column holds | Good dtype | Reason |
|---|---|---|
| Whole numbers in a known small range | `int8`, `int16`, `int32`, or unsigned types | Fewer bytes per value |
| Decimals where 7 digits of precision suffice | `float32` | Half the size of `float64` |
| Text with few distinct values | `category` | One copy of each string plus integer codes |
| Whole numbers with possible gaps | `Int64` | Keeps integers and uses `<NA>` for missing |
| Free-form text | `string` or `object` | Few repeats, so `category` saves little |
Failure modes to expect
Setting a dtype is an assertion about the data, and pandas checks it while parsing.
- If an
int32column contains a blank cell, the load fails because a plain integer dtype cannot hold a missing value. UseInt64for that column instead. - If a value is too large for the chosen width, pandas raises an error instead of silently wrapping around. Check the real range first.
- If a column named in
dtypeorusecolsis not in the file, you get an error. Typos in names surface immediately. - Precision is lost when you choose
float32for values that need more than about 7 significant digits. Keepfloat64for money totals or measurements that must stay exact.
Dates and large files
Dates are not set through dtype. Name them in parse_dates so they become datetime64 columns instead of strings:
import io
import pandas as pd
csv = io.StringIO("when,qty\n2026-01-05,3\n2026-01-06,4\n")
df = pd.read_csv(csv, parse_dates=["when"], dtype={"qty": "int16"})
print(df.dtypes)For files too big to hold at once, the same usecols and dtype arguments combine with chunksize. Each chunk then arrives already compact, and you can filter or aggregate it before keeping anything.
A repeatable workflow
- Read a small sample with
nrows=1000and inspectdf.dtypes. - Run
df.memory_usage(deep=True)to find the expensive columns. - Decide a dtype for each column using the table above and your knowledge of the data.
- Pass
usecolsanddtypeto the full read. - Compare
df.info(memory_usage="deep")before and after to confirm the saving.
Exercise
A CSV has columns user_id, country, age, and notes. You only need the first three. country has about 40 distinct values across millions of rows, and age is sometimes blank and never above 120. Write the read_csv call, and say why age should not use int8.
Show answer
Use pd.read_csv("users.csv", usecols=["user_id", "country", "age"], dtype={"user_id": "int64", "country": "category", "age": "Int8"}). The notes column is skipped, so it is never stored. country becomes a categorical because it has few distinct values. age cannot use plain int8 because blank cells are missing values, and a NumPy integer dtype cannot hold them, so the load would fail. The nullable Int8 fits the range 0 to 120 and stores blanks as <NA>.