Sub topic 11
Getting dtypes right when reading a CSV
What this chapter covers
Earlier chapters fixed dtypes after loading. This chapter moves the fix to the point where data enters pandas. Setting dtypes in pd.read_csv is often shorter and safer than repairing columns afterwards. It also avoids losing information, such as the leading zero in a zip code, before you can react.
This chapter assumes you know basic Python, can build and index a DataFrame and Series, and have used pd.read_csv before. It also assumes you know astype, pd.to_numeric, pd.to_datetime, and nullable dtypes such as Int64 from the earlier chapters. The examples use pandas 2.0 or later.
How read_csv chooses dtypes
A CSV file contains only text. read_csv has to decide what each column means, and it follows a fixed order.
Inference is convenient but guesses from the values it sees. Here is a small file with typical problems.
import io
import pandas as pd
csv = """zip,qty,price,status,order_date,shipped
02134,3,"1,200.50",shipped,2024-01-05,yes
10001,,85.00,pending,2024-01-06,no
60601,7,n/a,shipped,2024-01-07,yes
"""
df = pd.read_csv(io.StringIO(csv))
print(df.dtypes)
print(df["zip"].tolist())The output shows several problems:
| Column | Inferred dtype | Problem |
|---|---|---|
| `zip` | `int64` | `02134` became `2134`, so the leading zero is lost |
| `qty` | `float64` | One blank cell forces floats, so `3` becomes `3.0` |
| `price` | `object` | The thousands separator and `n/a` block numeric parsing |
| `status` | `object` | Repeated labels are stored as separate Python strings |
| `order_date` | `object` | Dates are still text |
| `shipped` | `object` | `yes` and `no` are not recognized as booleans |
The zip problem is the most serious because the damage happens during loading. Converting the integers back to text later cannot restore the zero.
Declaring dtypes with the dtype argument
The dtype argument takes a dictionary from column name to dtype. Use a dictionary when you know the columns. A single value such as dtype="string" applies to every column.
df = pd.read_csv(
io.StringIO(csv),
dtype={"zip": "string", "qty": "Int64", "status": "category"},
)
print(df.dtypes)
print(df["zip"].tolist())The zip codes are now ['02134', '10001', '60601']. The quantity column is Int64, so the blank cell becomes <NA> and the other values stay integers. The status column is category.
Parsing text values in the same call
read_csv has several arguments that handle the other columns, so they need no later cleanup.
| Argument | Purpose |
|---|---|
| `thousands=","` | Removes thousands separators before numeric parsing |
| `decimal=","` | Sets the decimal mark, for European-style numbers |
| `na_values=[...]` | Extra strings to treat as missing, such as `"n/a"` |
| `true_values`, `false_values` | Strings to read as `True` and `False` |
| `parse_dates=[...]` | Columns to parse as datetimes |
| `date_format="%Y-%m-%d"` | Explicit format used by `parse_dates` (pandas 2.0+) |
| `usecols=[...]` | Loads only the listed columns, which saves memory |
Putting them together:
df = pd.read_csv(
io.StringIO(csv),
dtype={"zip": "string", "qty": "Int64", "status": "category"},
thousands=",",
na_values=["n/a"],
true_values=["yes"],
false_values=["no"],
parse_dates=["order_date"],
date_format="%Y-%m-%d",
)
print(df.dtypes)
print(df)The result is string, Int64, float64, category, datetime64, and bool. The price "1,200.50" becomes 1200.5, and n/a becomes NaN. Because the price column is a float column, NaN is the missing-value marker.
What happens when a declared dtype does not fit
With to_numeric(errors="coerce"), a bad value becomes NaN. With read_csv, a declared dtype that cannot hold the data raises an error.
text = "a,b\n1,x\n,y\n3,z\n"
try:
pd.read_csv(io.StringIO(text), dtype={"a": "int64"})
except ValueError as err:
print("Failed:", err)
ok = pd.read_csv(io.StringIO(text), dtype={"a": "Int64"})
print(ok["a"].tolist())The first call fails because plain int64 cannot store the blank cell. The second succeeds because Int64 can hold <NA>. The same error appears for a text value like x in an integer column, where the message names the invalid literal.
The failure is often useful. It stops a bad file at the boundary of your program. If you instead want to load everything and inspect problems, use the read-as-text pattern below.
Load as text, then convert and validate
Reading every column as string loses nothing. You can then apply the conversions from earlier chapters and check which values failed.
raw = pd.read_csv(io.StringIO(csv), dtype="string")
price = pd.to_numeric(
raw["price"].str.replace(",", "", regex=False),
errors="coerce",
)
failed = raw.loc[price.isna() & raw["price"].notna(), "price"]
print(failed)Here n/a is reported as a failure, because it was not blank in the file. If you had listed it in na_values, it would have been treated as missing at load time and not reported. Choose between the two approaches deliberately. na_values is quiet and correct when you know which strings mean missing. Reading as text and coercing later is better when you want to see everything that did not parse.
Gotchas
Default missing-value strings
By default, read_csv treats strings such as NA, N/A, NaN, null, and the empty string as missing. This is a problem if NA is real data, for example a country code for Namibia. To control this, turn the defaults off and list your own:
codes = pd.read_csv(
io.StringIO("country\nNA\nUS\n"),
keep_default_na=False,
na_values=[""],
)
print(codes["country"].tolist())The output is ['NA', 'US'].
Datetimes belong in parse_dates
Do not put a datetime type in the dtype dictionary. Use parse_dates. If any value in a parse_dates column cannot be parsed, read_csv does not insert NaT. It leaves the whole column as object with the original text. This is easy to miss, so check the dtype after loading. If the column is still object, parse it afterwards with pd.to_datetime(df["order_date"], errors="coerce") and examine the failures.
Mixed types and DtypeWarning
For large files, the default C parser reads in chunks (low_memory=True) and infers a type for each chunk. A column that looks numeric in one chunk and contains text in another can end up with mixed Python types, and pandas emits a DtypeWarning. The fix is to declare the column's dtype. Setting low_memory=False also avoids it, but it uses more memory and only hides the real question of what the column should be.
Misspelled column names
Check df.dtypes after loading. A key in the dtype dictionary that does not match a column name does not necessarily raise an error, so a typo can leave a column on its inferred dtype without any warning.
Converters
The converters argument takes a function per column. It runs on every value as text, and the result replaces normal dtype handling. It is flexible but slow, because it calls Python code once per cell. Prefer dtype, thousands, na_values, and true_values when they can express what you need. Use converters only for custom rules such as stripping a unit suffix.
Nullable dtypes for the whole frame
Instead of naming every column, you can ask for nullable types across the frame:
df = pd.read_csv(io.StringIO(csv), dtype_backend="numpy_nullable")
print(df.dtypes)Integer columns with blanks become Int64, text columns become string, and boolean columns become boolean. Unlike plain inference, zip is still read as an integer here, so you still need a dtype entry for identifier-like columns. Treat dtype_backend as a way to keep missing values from changing column types, not as a substitute for deciding what each column means.
A practical checklist
- Run a first load with defaults and call
df.dtypesanddf.info()to see what pandas guessed. - Name identifier columns (zip codes, account numbers, phone numbers) as
string. - Name columns with blanks as
Int64,boolean, orstringso missing values keep the type. - Add
thousands,decimal,na_values, andtrue_values/false_valuesfor known text patterns. - List date columns in
parse_dates, withdate_formatwhen the format is known. - Add
categoryfor columns of repeated labels. - Check
df.dtypesagain. Any date column still showingobjectneedspd.to_datetime(..., errors="coerce")and a look at the failures.
Exercise
A CSV has a column account with values such as 00123 and 04567, and a column visits with some blank cells. Write the read_csv call that keeps the leading zeros and stores visits as integers with missing values preserved. Why does dtype={"visits": "int64"} fail?
Show answer
Use pd.read_csv(path, dtype={"account": "string", "visits": "Int64"}). Reading account as string keeps the text exactly as written, so 00123 is not turned into 123. The plain int64 dtype cannot represent missing values, so a blank cell makes read_csv raise a ValueError. The nullable Int64 dtype stores the blank as <NA> and keeps the other values as integers.
Exercise
You load a file with parse_dates=["shipped_on"], but df["shipped_on"].dtype is object. What most likely happened, and what do you do next?
Show answer
At least one value in the column could not be parsed, so read_csv left the whole column as the original text instead of inserting NaT. Convert it afterwards with pd.to_datetime(df["shipped_on"], format=..., errors="coerce"), then compare the result with the original to find non-missing values that became NaT and fix or report them.