Sub topic 10
Setting dtypes and columns when reading files
This chapter assumes you know how a DataFrame stores columns as typed arrays, the difference between object and NumPy dtypes, and how memory_usage(deep=True) works. It also assumes you have used pd.read_csv at a basic level. The examples target pandas 2.x.
Why load-time choices matter
By default, read_csv guesses a dtype for every column. Whole numbers become int64, decimals become float64, and anything else becomes object. If you load first and shrink later, you pay for the large version first. A wide file with a text column can use several times more memory during the load than the final frame needs. On a small machine, that peak can be the point where the load fails.
Telling the parser what you want avoids this. You choose which columns to read, what type each one gets, and how dates and missing values are handled. The parser then builds compact columns directly.
Reading only the columns you need
The usecols argument takes a list of column names or positions. Columns you skip are never converted into arrays, so they cost no memory in the result.
The dtype argument takes a dict that maps column names to dtypes. Columns you leave out of the dict are still inferred.
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)Here id is int32, city is category, and score is float32. You can also pass one dtype for every column, such as dtype=str. That is useful for identifiers like zip codes, where leading zeros must survive.
usecols also accepts a function. It is called with each column name and returns True for the columns to keep. This helps with wide files where you want, for example, every column that starts with m_.
Measuring the gain
Check the result instead of assuming it. The next script builds a CSV in memory, loads it twice, and compares deep memory totals.
import io
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 200_000
raw = pd.DataFrame({
"id": np.arange(n),
"city": rng.choice(["Oslo", "Lima", "Pune"], size=n),
"score": rng.random(n),
"note": "unused text column",
})
text = raw.to_csv(index=False)
default = pd.read_csv(io.StringIO(text))
tuned = pd.read_csv(
io.StringIO(text),
usecols=["id", "city", "score"],
dtype={"id": "int32", "city": "category", "score": "float32"},
)
print(default.memory_usage(deep=True).sum())
print(tuned.memory_usage(deep=True).sum())The tuned frame is much smaller for three reasons. The note column is skipped, city is stored as small integer codes, and the numeric columns are half as wide. Exact byte counts depend on your pandas version, so compare the two numbers instead of expecting a fixed value.
Choosing dtypes for each kind of column
| Column holds | Suggested `dtype` | Notes |
|---|---|---|
| Small whole numbers, no gaps | `"int8"`, `"int16"`, `"int32"`, `"uint8"` | Pick the smallest type that holds the range. |
| Whole numbers with gaps | `"Int64"` (nullable) | A plain NumPy integer cannot hold a missing value. |
| Decimals | `"float32"` | Halves memory but keeps about 7 significant digits. |
| Few distinct strings | `"category"` | Best when values repeat many times. |
| Free text | `"string"` or leave as `object` | Little to gain from a smaller dtype. |
| True/False with gaps | `"boolean"` | NumPy `bool` has no missing value. |
| Dates and times | `parse_dates=[...]` | Not set through `dtype`. |
Integers and missing values
A NumPy integer dtype has no way to represent a missing value. If you request one for a column that has empty fields, the parser stops with an error.
import io
import pandas as pd
csv = "id,age\n1,30\n2,\n3,41\n"
try:
pd.read_csv(io.StringIO(csv), dtype={"age": "int64"})
except ValueError as err:
print("ValueError:", err)
df = pd.read_csv(io.StringIO(csv), dtype={"age": "Int64"})
print(df.dtypes)
print(df["age"])The first call raises a ValueError that mentions NA values in an integer column. The second call succeeds because Int64 stores the gap as <NA>. If you leave the dtype out, pandas silently promotes age to float64 with NaN, which is the promotion you learned about in the missing-values chapter.
Dates are separate from dtype
Passing a datetime dtype in the dtype dict does not parse dates. Use parse_dates with the column names instead. Without it, a date column loads as object strings, which are among the most expensive things you can keep in memory. If your dates use an unusual format, parse them after loading with pd.to_datetime(col, format=...). Giving the format explicitly is also faster than letting pandas guess.
Categoricals and their categories
With dtype="category", pandas learns the categories from the data it reads. Two details matter.
- The inferred categories are strings, even when the column looks numeric. If you need numeric categories, convert them afterward, for example with
pd.to_numericoncat.cat.categories. - Different files, or different chunks of one file, can produce different category sets. Concatenating them then yields
object, and you lose the memory savings.
Both problems go away if you declare the categories yourself with pd.CategoricalDtype. A value that is not in your list becomes missing, so use this only when the list is complete.
import io
import pandas as pd
csv = (
"when,city,qty\n"
"2026-01-01,Oslo,3\n"
"2026-01-02,Lima,5\n"
"2026-01-03,Pune,2\n"
"2026-01-04,Oslo,7\n"
"2026-01-05,Lima,1\n"
)
cities = pd.CategoricalDtype(["Oslo", "Lima", "Pune"])
chunks = pd.read_csv(
io.StringIO(csv),
dtype={"city": cities, "qty": "int16"},
parse_dates=["when"],
chunksize=2,
)
df = pd.concat(chunks, ignore_index=True)
print(df.dtypes)
print(df["city"].cat.categories)Every chunk shares the same categorical dtype, so pd.concat keeps city as a category. The when column comes out as a datetime64 dtype.
Reading in chunks
The chunksize argument makes read_csv return an iterator of smaller frames. Use it when the file is too large to hold at once but you can reduce each piece before keeping it. Typical patterns are filtering rows, aggregating, or keeping a few columns.
Two rules keep chunked reads predictable:
- Always set
dtypeexplicitly. Otherwise each chunk infers its own types, and a column that is all integers in one chunk and has a gap in the next will change dtype between chunks. - Reduce each chunk before you collect it. Concatenating full-size chunks gives you the same memory problem you started with.
Mixed types and `low_memory`
By default the C parser reads big files in internal pieces and infers types per piece. If one column holds numbers in the first pieces and a stray string later, you can get a DtypeWarning about mixed types, and the column ends up as object with both integers and strings inside. Setting dtype for that column fixes the problem, because inference no longer runs. Decide whether the odd values are errors. If they are, load the column as str and clean it, or convert with pd.to_numeric(col, errors="coerce").
Missing-value markers
Real files use many spellings for "no data". Pandas already treats empty fields, NA, NaN, and null as missing. Add your own markers with na_values, for example na_values=["-", "n/a", "9999"]. The argument also takes a dict, so a sentinel like 9999 can be missing in one column and a real value in another. Handle sentinels at load time, because a stray "-" in a numeric column forces the whole column to object.
Nullable and Arrow backends
If you want nullable dtypes everywhere, you do not have to list each column. Pass dtype_backend="numpy_nullable" and read_csv returns Int64, Float64, boolean, and string columns where appropriate. With dtype_backend="pyarrow", the columns use Arrow-backed dtypes. You can combine this with an explicit dtype dict, and the dict wins for the columns it names. Arrow-backed columns are covered in their own chapter.
Other readers have similar controls. pd.read_parquet(path, columns=[...]) reads only the listed columns from disk. pd.read_excel accepts usecols and dtype. Parquet files also store their own dtypes, so you rarely need a dtype argument there.
A practical workflow
For an unfamiliar file, follow these steps.
- Read a sample with
pd.read_csv(path, nrows=1000)and look atdf.dtypesanddf.nunique(). - Decide per column: skip it, give it a compact numeric type, make it a category, or parse it as a date.
- Write the choices into one
dtypedict and ausecolslist, and keep them in your code so the load is repeatable. - Load the full file and compare
memory_usage(deep=True).sum()against a default load on a subset.
Beware of ranges. A sample of 1000 rows may show values that fit in int8, while the full file contains larger ones. Check min() and max() on the full data, or use a wider type than the sample suggests. An out-of-range value in a narrow integer type fails to parse with an error or wraps to a wrong number, depending on the path. Neither is something you want to find in production.
Common errors
ValueErrorabout NA values in an integer column. The column has gaps. UseInt64, orfloat64, or fill the gaps throughna_valueshandling.- A
categorycolumn becameobjectafter concatenation. The pieces had different category sets. Declare a sharedCategoricalDtype. - Leading zeros disappeared. The column was inferred as integer. Load it as
str. - A date column is
object. You passed it indtypeinstead ofparse_dates. DtypeWarningabout mixed types. Setdtypefor that column, or clean its values.- Values turned into
NaNunexpectedly. A fixedCategoricalDtypedid not list every value in the file.
Exercise
A CSV has columns user_id (whole numbers 1 to 50,000), country (about 40 distinct codes across 2 million rows), signup (an ISO date), age (whole numbers, some fields empty), and comment (long free text that you do not need). Write the read_csv arguments you would use, and say why each choice reduces memory or avoids an error.
Show answer
Use usecols=["user_id", "country", "signup", "age"] so the comment column is never loaded. Use dtype={"user_id": "int32", "country": "category", "age": "Int64"} and parse_dates=["signup"]. int32 holds values up to about 2 billion, so it covers 50,000 at half the size of int64. uint16 would also fit, since 50,000 is below 65,535, if you are sure the range will not grow. category stores 40 strings once and a small integer code per row, instead of 2 million Python string pointers. Int64 keeps age as integers and stores the empty fields as <NA>, and a plain int dtype would raise a ValueError. parse_dates turns signup into a datetime64 column instead of object strings.
Exercise
You read a 10 GB file with chunksize=1_000_000 and dtype={"city": "category"}, then call pd.concat on the chunks. The result has city as object. What happened, and how do you fix it?
Show answer
Each chunk built its own category set, because different chunks contained different cities. pd.concat cannot keep a categorical when the category sets differ, so it falls back to object. Fix it by passing a shared pd.CategoricalDtype with the full list of cities in the dtype dict, so every chunk uses the same categories. If you do not know the list in advance, make a first pass that collects the distinct values. Another option is to call union_categoricals on the chunks.