Reading two rows at a time should still leave an unknown quantity visible in the final report. In this example, East has eight known units and one missing quantity, so its complete total stays unknown.
Use chunksize to read portions of a CSV, then carry row counts, known-value counts, and known units forward between chunks. The five fictional records below include both an empty quantity and a genuine zero.

Start with the input and its missing-value rule
This CSV has two columns: a region label and a nonnegative whole-number quantity. An empty units field means unknown. The West record containing 0 is an observed quantity and must remain part of the known-value count.
| region | units |
|---|---|
| East | 5 |
| West | 0 |
| East | Empty field |
| West | 7 |
| East | 3 |
The complete CSV text is included in the code. StringIO makes that text readable as a file-like object; you do not need an input file or a download. Run the example with pandas installed. It was executed with Python 3.11.3 and pandas 2.3.3.
Update one regional summary after each chunk
from io import StringIO
from collections import defaultdict
import pandas as pd
csv_text = """region,units
East,5
West,0
East,
West,7
East,3
"""
def summarize_chunks(text, chunksize=2):
if type(chunksize) is not int or chunksize < 1:
raise ValueError("Use a positive integer chunk size.")
totals = defaultdict(lambda: {"rows": 0, "known": 0, "known_units": 0})
with pd.read_csv(
StringIO(text), chunksize=chunksize,
dtype={"region": "string", "units": "Int64"},
keep_default_na=False, na_values={"units": [""]},
) as reader:
for chunk in reader:
if list(chunk.columns) != ["region", "units"]:
raise ValueError("Expected the columns region,units in that order.")
if chunk["region"].isna().any() or chunk["region"].str.strip().eq("").any():
raise ValueError("Every row needs a region.")
if chunk["units"].dropna().lt(0).any():
raise ValueError("Units must be nonnegative whole numbers.")
for region, part in chunk.groupby("region", sort=False):
entry = totals[region]
entry["rows"] += len(part)
entry["known"] += int(part["units"].notna().sum())
entry["known_units"] += sum(int(x) for x in part["units"].dropna())
if entry["known_units"] > 2**63 - 1:
raise ValueError("A regional total exceeds the Int64 range.")
if not totals:
raise ValueError("The CSV needs at least one data row.")
result = pd.DataFrame.from_dict(totals, orient="index").rename_axis("region")
result["missing"] = result["rows"] - result["known"]
result["complete_units"] = result["known_units"].astype("Int64").where(
result["missing"].eq(0)
)
return result[["rows", "known", "missing", "known_units", "complete_units"]]
summary = summarize_chunks(csv_text, chunksize=2)
print(summary.to_string())
Output:
rows known missing known_units complete_units
region
East 3 2 1 8 <NA>
West 2 2 0 7 7
Read the partial and complete totals separately
East appears in three records. Two quantities are known, and 5 plus 3 gives eight known units. The third quantity remains unknown, so complete_units displays <NA>. Eight is a partial sum, not an established total for every East record.
West has two records and two known quantities. Its zero contributes no units but still counts as observed. With no missing quantities, its complete total is 7.
The accumulator stores three values per region: rows, known quantities, and known units. The final step obtains the missing count from rows minus known quantities. Only regions with no missing quantities receive a complete total. A region with every quantity missing still appears in the report.
Keep the same types and rules across chunks
The explicit "Int64" dtype accepts nullable whole numbers. keep_default_na=False and the per-column na_values setting declare empty units fields missing. A literal region label such as NA remains text. Choose those rules from the export specification before processing a larger input.
The function rejects blank region labels, negative quantities, and an unexpected column list. pandas rejects malformed whole-number quantities. Region labels are otherwise compared exactly: "East" and " East" remain different groups. Decide whether any spelling or spacing changes are allowed before grouping.
Each known quantity is added through a Python integer. The explicit range check stops a regional total above the nullable signed 64-bit limit before the final column is created. This example is for whole units; measured decimal quantities need a separate type and arithmetic policy.
A header-only input raises ValueError because this report requires at least one record. An entirely empty input raises pandas’ EmptyDataError. Neither case is reported as a region with zero units.
Check chunk boundaries before using a larger input
Change the call to chunk sizes 1, 3, or 20. The same five records must produce the same summary. A region can appear in several chunks, so its earlier counts and units must survive when a later chunk arrives.
This demonstration already holds its small CSV text in memory. For a large existing input, supply a local CSV path or readable stream to read_csv instead of first loading the entire file into one string. Keep the same types and missing-value settings.
Chunking limits how many input rows are processed together. The accumulator still grows with the number of distinct regions; this is not a fixed-memory guarantee. Avoid retaining every chunk in a list if the intended output is only this summary.
Reconcile the row count and missing count as well as the known sum. For the decisions behind missing markers, see finding and filling missing values in pandas. Keep an unknown quantity unknown until the source establishes its value.
Further reading
- pandas documentationread_csvReview chunk iteration, explicit types, and missing-value settings.
- pandas user guideNullable integer data typesKeep unknown whole-number quantities alongside observed integers.
- MathBlogCombine multiple CSV filesUse a separate workflow when your task is stacking several compatible exports.