Read and summarize larger datasets
3.1.1
Read only needed data and compute summaries in batches with explicit aggregation.
On this page
Limit columns and inspect memory use
Read only needed columns with usecols for CSV or columns for Parquet. Choose appropriate dtypes and inspect memory_usage(deep=True) on the resulting frame. Measure before deciding whether an optimization helps.
Accumulate partial sums and counts
read_csv(chunksize=...) returns an iterator over chunks. For a global mean, add all valid values and divide by their total count. Chunk means can differ in sample size, so averaging them directly can skew the result.
from io import StringIO
import pandas as pd
source = StringIO("amount\n4\n2\n8\n")
total = count = 0
for chunk in pd.read_csv(source, chunksize=2):
total += chunk["amount"].sum()
count += chunk["amount"].count()
print(total, count, round(float(total / count), 2))
Example output
14 3 4.67