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 Pathimport pandas as pdPath("trades.csv").write_text("""date,ticker,code,price,size2024-04-01,AAA,012340005,48.44,9312024-04-01,BBB,023450006,25.10,1202024-04-02,CCC,534560007,125.30,502024-04-02,AAA,012340005,48.60,3002024-04-30,BBB,023450006,24.90,752024-04-30,CCC,534560007,126.00,10""")guessed = pd.read_csv("trades.csv")print(guessed.dtypes)print(guessed["code"].unique())
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.