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.
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.
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.