How do I load a CSV with the column types my analysis needs?

Tell read_csv the type of each column, so codes keep their leading zeros, repeated tickers become categories and dates work as dates.

After this lesson, you can read a trade file so that identifiers keep their zeros, tickers take little memory and dates work in arithmetic.

What does pandas guess from the values?

pd.read_csv guesses each column’s type from its values, so an identifier made only of digits becomes an integer and loses its leading zero. AAA’s code 012340005 becomes 12340005, which no longer matches the nine-character code in another file.

The file holds six made-up trades, with a date, a ticker, a nine-digit code, a price in dollars and a size in shares. Path(...).write_text() writes the text into a file, so the lesson reads a real file. .dtypes shows each column’s type.

The following box writes the file and reads it with the guessed types.

from pathlib import Path
import pandas as pd

Path("trades.csv").write_text("""date,ticker,code,price,size
2024-04-01,AAA,012340005,48.44,931
2024-04-01,BBB,023450006,25.10,120
2024-04-02,CCC,534560007,125.30,50
2024-04-02,AAA,012340005,48.60,300
2024-04-30,BBB,023450006,24.90,75
2024-04-30,CCC,534560007,126.00,10
""")
guessed = pd.read_csv("trades.csv")
print(guessed.dtypes)
print(guessed["code"].unique())
date       object
ticker     object
code        int64
price     float64
size        int64
dtype: object
[ 12340005  23450006 534560007]

The dates arrive as text, of type object.

How do I declare the types when I read the file?

dtype={"code": str, "ticker": "category"} reads the codes as text and the tickers as categories, and parse_dates=["date"] reads the dates as dates. The codes keep their zeros, and the dates can be subtracted, so the trades span 29 calendar days.

A category stores each distinct ticker once and gives every row a small integer code that points to it, so millions of rows with three tickers take far less memory than the same text. .cat.categories lists the labels and .cat.codes the code of each row.

The following box reads the file with declared types.

trades = pd.read_csv("trades.csv", dtype={"code": str, "ticker": "category"}, parse_dates=["date"])
print(trades.dtypes)
print(trades["code"].unique())
print(trades["ticker"].cat.categories.tolist(), trades["ticker"].cat.codes.tolist())
print(trades["date"].max() - trades["date"].min())
date      datetime64[ns]
ticker          category
code              object
price            float64
size               int64
dtype: object
['012340005' '023450006' '534560007']
['AAA', 'BBB', 'CCC'] [0, 1, 2, 0, 1, 2]
29 days 00:00:00

Subtracting the text dates of the guessed read would raise a TypeError.

Your turn

Turn the text codes into a category and print its labels. You should see the three nine-digit codes, with the zeros of AAA and BBB.

.astype("category") stores each distinct code once.

print(trades["code"].astype("category").cat.categories.tolist())
['012340005', '023450006', '534560007']