Pandas Chunked CSV Aggregation
Aggregate CSV files larger than memory with pandas chunksize iteration, accumulating partial sums and merging into a final report.
Code
import pandas as pd
CHUNK_ROWS = 100_000
def aggregate_csv(path: str) -> pd.DataFrame:
partials: list[pd.DataFrame] = []
total_rows = 0
reader = pd.read_csv(
path,
chunksize=CHUNK_ROWS,
usecols=['region', 'category', 'amount', 'quantity'],
dtype={'region': 'category', 'category': 'category'},
)
for chunk in reader:
total_rows += len(chunk)
partial = (
chunk
.groupby(['region', 'category'], observed=True)
.agg(revenue=('amount', 'sum'), units=('quantity', 'sum'))
.reset_index()
)
partials.append(partial)
combined = pd.concat(partials, ignore_index=True)
final = (
combined
.groupby(['region', 'category'], observed=True)
.agg(revenue=('revenue', 'sum'), units=('units', 'sum'))
.reset_index()
.sort_values('revenue', ascending=False)
)
final.attrs['source_rows'] = total_rows
return final
report = aggregate_csv('sales/2026-10-transactions.csv')
print('regions reported:', len(report))
print('source rows:', report.attrs['source_rows'])How it works
Structurally, expect the function aggregate_csv and nothing else.
Repetition is confined to for chunk in reader — the rest of the file is straight-line.
Points of care
- Plan for an install step:
pandasis a real dependency, resolved by the package manager.
Putting it to use
Entry signature: def aggregate_csv(path: str) -> pd.DataFrame
Look for the regions reported:, source rows: prefixes when the file runs; they tie each line to its step.
The surface worth importing is aggregate_csv; the helpers around it are private to the snippet.
Interactive Tools for This Topic
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
FAQ
- What does this need from the package registry?
- These are real dependencies: `pandas`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.