How do I save a table so it loads fast and keeps its types?

Save a table as a Parquet file, which stores each column with its type and compressed, read it back with its dates and categories intact, and read only the columns a calculation needs.

After this lesson, you can save a month of trades as a Parquet file, check that the values and column types survive the read, and load only the two columns a calculation needs.

How does a Parquet file differ from a CSV?

trades.to_parquet(path) stores each column’s values together, with the column’s type and with compression, so the million made-up trades fit in less than 10 MB while the CSV needs more, and pd.read_parquet returns the dates as timestamps, the tickers as a category and the sizes as 32-bit integers. The table read back equals the original.

The trades have a date in April 2024, a ticker from AAA to EEE, a price in dollars per share and a size in shares. Repeated values, five tickers and 22 dates, compress well. pd.read_csv infers types from text, so the dates and tickers come back as text, object, and the sizes as int64. pandas writes Parquet with the package pyarrow, installed with python -m pip install pyarrow.

Code: the made-up trades
import shutil
from pathlib import Path

import numpy as np
import pandas as pd

demo = Path("parquet_demo")
shutil.rmtree(demo, ignore_errors=True)
demo.mkdir()
rng = np.random.default_rng(9)
price_level = {"AAA": 170.0, "BBB": 180.0, "CCC": 410.0, "DDD": 880.0, "EEE": 170.0}
n = 1_000_000
trades = pd.DataFrame({"date": rng.choice(pd.bdate_range("2024-04-01", "2024-04-30"), n), "ticker": pd.Categorical(rng.choice(list(price_level), n))})
trades["price"] = (trades["ticker"].map(price_level).astype(float) * rng.normal(1, 0.01, n)).round(2)
trades["size"] = rng.integers(1, 1_000, n).astype("int32")
trades = trades.sort_values("date", ignore_index=True)

The following box writes both files, tests them against a 10 MB limit and compares the types read back.

trades.to_csv(demo / "trades.csv", index=False)
trades.to_parquet(demo / "trades.parquet", index=False)
print((demo / "trades.csv").stat().st_size <= 10_000_000, (demo / "trades.parquet").stat().st_size <= 10_000_000)
from_parquet = pd.read_parquet(demo / "trades.parquet")
print(pd.DataFrame({"csv": pd.read_csv(demo / "trades.csv").dtypes, "parquet": from_parquet.dtypes}))
print(from_parquet.equals(trades))
False True
            csv         parquet
date     object  datetime64[ns]
ticker   object        category
price   float64         float64
size      int64           int32
True

How do I read only the columns I need?

pd.read_parquet(path, columns=["ticker", "size"]) reads only the two columns a share total needs and skips the stored data of the dates and prices, and grouping by ticker gives CCC 99,956,806 shares. filters=[("ticker", "==", "CCC")] also reads only the rows that pass a test.

observed=True keeps only the tickers with trades, because a category knows all its labels. The less a read has to decode, the faster it runs, and how much faster depends on the machine.

The following box reads the two columns and totals the shares.

two_columns = pd.read_parquet(demo / "trades.parquet", columns=["ticker", "size"])
print(two_columns.groupby("ticker", observed=True)["size"].sum())
ticker
AAA    100379635
BBB    100112911
CCC     99956806
DDD     99803362
EEE     99898971
Name: size, dtype: int32

Your turn

Read only CCC’s prices and sizes and print the number of trades and their volume-weighted average price, the traded dollars divided by the shares. You should see 200,204 trades and 409.99.

filters keeps the CCC rows while reading.

ccc = pd.read_parquet(demo / "trades.parquet", columns=["price", "size"], filters=[("ticker", "==", "CCC")])
print(len(ccc), f"{(ccc['price'] * ccc['size']).sum() / ccc['size'].sum():.2f}")
200204 409.99