Sub topic 11
Loading less data: usecols, dtype, and Parquet
The fastest data to process is data you never load. This chapter covers three ways to cut read time and memory before your pipeline starts: reading only the columns you need, choosing compact dtypes at read time, and storing data in Parquet instead of CSV.
It assumes you know basic Python and pandas DataFrames, and that you have seen dtypes and memory measurement in the previous chapter.
Why reading is often the bottleneck
A CSV file is plain text. pandas must split every line, guess a type for every column, and build Python-level objects for text. If the file has 40 columns and you use 3, you pay for 37 columns of work and memory you never needed.
Profiling (covered earlier) often shows read_csv as the top entry. When it does, the fixes below usually beat any later optimization.
Read only the columns you need
Pass usecols to skip the rest. The unused columns are never converted into pandas objects.
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
)You can also limit rows with nrows=1000 while developing. That gives a fast feedback loop, but remember that results from a sample can differ from results on the full file.
Choose dtypes while reading
Without hints, pandas reads integers as int64, decimals as float64, and text as Python object. Passing dtype sets compact types at read time, so the large version never exists in memory.
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
dtype={"region": "category", "amount": "float32"},
)
print(df.memory_usage(deep=True))category suits columns with few distinct values, such as region or status. float32 halves the memory of float64, but it keeps only about 7 significant digits.
Save to Parquet
Parquet is a binary, columnar file format. It stores each column separately, keeps the dtype of each column, and compresses well. Reading it back needs no type guessing.
import pandas as pd
df = pd.read_csv(
"orders.csv",
usecols=["order_id", "region", "amount"],
dtype={"region": "category", "amount": "float32"},
)
df.to_parquet("orders.parquet")
subset = pd.read_parquet("orders.parquet", columns=["region", "amount"])
print(subset.dtypes)The Parquet calls need pyarrow or fastparquet installed. You can install the first with pip install pyarrow.
Because Parquet is columnar, columns=[...] reads only those columns from disk. In a CSV, the reader must scan every line even when it keeps only some fields.
CSV compared with Parquet
| Property | CSV | Parquet |
|---|---|---|
| Format | Text | Binary, columnar |
| Dtypes stored | No, guessed on each read | Yes |
| Read a few columns | Scans the whole file | Reads only those columns |
| Human readable | Yes | No |
| Typical file size | Large | Much smaller with compression |
Use CSV to exchange data with people and tools that need it. Use Parquet for intermediate files that your own pipeline writes and reads repeatedly.
The workflow
Check the gain
Measure, as in earlier chapters. Time both reads and compare memory.
from time import perf_counter
import pandas as pd
start = perf_counter()
full = pd.read_csv("orders.csv")
print(f"full CSV: {perf_counter() - start:.3f}s")
start = perf_counter()
small = pd.read_parquet("orders.parquet", columns=["region", "amount"])
print(f"Parquet cols: {perf_counter() - start:.3f}s")
print(full.memory_usage(deep=True).sum(), small.memory_usage(deep=True).sum())Common errors
- A name in
usecolsis misspelled.read_csvraises aValueErrorlisting the missing column. Checkpd.read_csv("orders.csv", nrows=0).columnsfirst. dtypefails on missing values. A plain integer dtype cannot holdNaN. Use"Int32"(nullable) or keepfloat.- Parquet import error. Neither
pyarrownorfastparquetis installed. - Verification skipped. After changing dtypes, compare results with the original, as in the chapter on verifying results.
Exercise
A 2 GB CSV has 30 columns, and your analysis uses only region and amount. region has five distinct values. Name three changes that reduce load time and memory, and say which one helps repeated runs most.
Show answer
Pass usecols=["region", "amount"] to skip 28 columns. Pass dtype={"region": "category"} (and possibly "amount": "float32" if the precision is acceptable) to shrink memory. Convert the data to Parquet. Parquet helps repeated runs most, because later runs read only the two needed columns, with stored dtypes and no text parsing.