Sub topic 3
Choosing dtypes and measuring memory
Assume you know Python, pandas DataFrames, column selection, filtering, groupby, merge, and basic NumPy operations. Optimize only after measuring both runtime and memory.
Choose dtypes deliberately
Pandas dtypes affect memory use and operation speed. Repeated strings often fit category, while numeric columns may use smaller types when their ranges allow it.
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))Use memory_usage(deep=True) for object and string columns. Check that smaller numeric types cannot overflow, and remember that category is best when a column has relatively few distinct values.
Faster groupby and merge patterns
Use built-in groupby operations instead of Python functions where possible. transform returns a value aligned with the original rows:
sales["share"] = (
sales["amount"]
/ sales.groupby("region")["amount"].transform("sum")
)Before a merge, select only required columns and ensure join keys have compatible dtypes. Remove duplicate keys or validate the relationship when appropriate.
Build frames without repeated concatenation
Appending or concatenating inside a loop repeatedly copies the growing DataFrame. Collect pieces, then concatenate once.
result = pd.concat(parts, ignore_index=True)Load less data
Use usecols to read only needed columns. Specify dtypes during loading so pandas does not first create larger temporary objects. For repeated analysis, save a columnar Parquet file:
df.to_parquet("orders.parquet")
subset = pd.read_parquet(
"orders.parquet",
columns=["region", "amount"],
)Parquet supports column selection and usually avoids parsing unused fields.
Remaining hot spots
query and eval can reduce temporary objects for suitable column expressions:
recent = df.query("amount > 100")
df.eval("net = amount * 0.9", inplace=True)Benchmark them against ordinary expressions. Use Numba only for a measured, numerical hot spot that vectorization cannot express. It adds compilation and type constraints.
When pandas is not enough
Read large files in chunks, aggregate each chunk, and combine the smaller results. If data still exceeds memory or requires distributed execution, consider a database, Polars, or Dask.
Exercise
Why should you concatenate DataFrame pieces after a loop instead of during every iteration?
Show answer
Each in-loop concatenation copies the growing result, so collecting pieces and concatenating once avoids repeated copying.