Sub topic 11
Getting dtypes right when reading a CSV
This chapter assumes you can load a CSV with pd.read_csv, and that you know the astype, pd.to_numeric and pd.to_datetime conversions from earlier chapters. Here you will move those conversions into the load step, so the DataFrame has the right types from the start.
Why fix types at load time
By default, read_csv reads the file and guesses each column's type. The guesses go wrong in predictable ways:
- A zip code like
02134becomes the integer2134, and the leading zero is lost for good. - One bad entry such as
n/aturns a whole numeric column intoobject. - Dates stay as plain text.
Correcting these after loading means the information may already be damaged. Telling pandas what you expect up front avoids that. It also skips one pass over the data.
The dtype argument
dtype takes a dictionary that maps column names to types. You can use NumPy names, nullable names such as "Int64", or "string" and "category".
import io
import pandas as pd
csv = "zip,status,order_date\n02134,shipped,2024-01-05\n10001,pending,2024-01-06\n"
df = pd.read_csv(
io.StringIO(csv),
dtype={"zip": "string", "status": "category"},
parse_dates=["order_date"],
)
print(df.dtypes)
print(df["zip"].tolist())The zip codes stay as '02134' and '10001'. The status column is stored as a category, which saves memory when labels repeat. The parse_dates argument turns order_date into datetime64.
Missing values and number formats
A plain NumPy integer type cannot hold a missing value. If you ask for "int64" on a column with blanks, pandas raises an error. Use the nullable "Int64" instead.
Other arguments describe how the file writes its numbers and its missing values:
na_valueslists extra strings to treat as missing, such as"n/a".thousandsnames the separator inside numbers, so"1,200"parses as1200.
import io
import pandas as pd
csv = """zip,status,qty,price,order_date
02134,shipped,3,"1,200",2024-01-05
10001,pending,,85,2024-01-06
60601,shipped,7,n/a,bad
"""
df = pd.read_csv(
io.StringIO(csv),
dtype={"zip": "string", "status": "category", "qty": "Int64"},
thousands=",",
na_values=["n/a"],
)
df["order_date"] = pd.to_datetime(df["order_date"], errors="coerce")
print(df.dtypes)
print(df)Here qty is Int64 with one <NA>. The column price is float64, because the n/a became NaN and the quoted "1,200" became 1200. The last date, bad, becomes NaT.
I did not use parse_dates for order_date in this example. When a column contains a value that cannot be parsed, parse_dates leaves the whole column as text. Reading the column as text and then calling pd.to_datetime(..., errors="coerce") gives you control over the failures.
Choosing a approach
Common errors
- A ValueError about NA values in an integer column. You requested
int64for a column with blanks. Use"Int64". - A ValueError when converting text to a number. A value like
n/aor$5cannot be parsed. Read the column as"string", clean it, and convert it withpd.to_numeric. You can also add the marker tona_values. - A column name in
dtypethat does not match. Names must match the header exactly, including spaces and capitalization. A misspelled key is ignored. - Leading zeros still lost. Identifier columns such as zip codes, phone numbers and product codes should be
"string", not a number type.
Exercise
A CSV has a column account_id with values like 007421, and a column visits where some cells are empty. Which dtype dictionary should you pass to read_csv, and why?
Show answer
Use dtype={"account_id": "string", "visits": "Int64"}. The string type keeps the leading zeros in 007421. Int64 is a nullable integer type, so the empty cells become <NA> and the column does not fall back to float or raise an error.