Sub topic 9
Combining Grouped Results from Many Chunks
This chapter assumes you know basic pandas groupby and aggregation, you can iterate over a read_csv reader with chunksize, and you have seen the pattern of keeping a running total across chunks. Here we extend that pattern to grouped results, where every chunk produces its own small table of per-group values that must be merged correctly.
The problem: groups span chunks
A chunk is a slice of rows in file order. Rows for one group, such as the region "north", are usually scattered through the whole file. If you call groupby on each chunk, you get a partial answer for each group in that chunk only. The same group appears in many chunks, and each appearance holds only a piece of the final value.
Two things follow from this:
- You cannot print or keep each chunk's result as the final answer. You must merge the pieces.
- The merge rule depends on the statistic. Sums and counts add. Minimums and maximums take the minimum or maximum of the pieces. A mean must be rebuilt from a combined sum and a combined count.
The memory benefit comes from the size of the partial results. A chunk of 200,000 rows may collapse to a table of a few dozen rows if there are a few dozen groups. You hold one chunk plus one small running table, never the whole file.
A complete grouped aggregation
The following script builds a small sales file so you can run it as shown. It then aggregates it with a deliberately small chunk size so that every group spans several chunks.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 1_000
pd.DataFrame(
{
"region": rng.choice(["north", "south", "east", "west"], size=n),
"amount": rng.integers(1, 500, size=n),
}
).to_csv("sales.csv", index=False)
totals = None
with pd.read_csv("sales.csv", usecols=["region", "amount"], chunksize=200) as reader:
for chunk in reader:
part = chunk.groupby("region")["amount"].agg(["sum", "count"])
totals = part if totals is None else totals.add(part, fill_value=0)
totals["mean"] = totals["sum"] / totals["count"]
print(totals)
full = pd.read_csv("sales.csv").groupby("region")["amount"].agg(["sum", "count", "mean"])
print(np.allclose(totals.sort_index(), full.sort_index()))The last two lines compare the chunked result with a normal in-memory result. This is a good habit when you test chunked code on a file small enough to load: the two answers should match.
Why `add` with `fill_value=0`
DataFrame.add aligns two tables by index label, here the region names. If a region appears in the running table but not in the new partial table, a plain + would produce NaN for that region. Passing fill_value=0 treats a missing label as zero, so the region keeps its running value. The same holds in the other direction, when a region appears for the first time in a later chunk.
One side effect is worth knowing. After add, the columns can change from integer to float, because alignment with missing labels introduces NaN internally before the fill. Counts such as 3.0 are harmless for arithmetic. If you want integers at the end, convert once after the loop:
totals["count"] = totals["count"].astype("int64")Other ways to merge partial results
add is convenient for sums and counts. Other approaches are useful when you need different statistics, or when you want to avoid index alignment.
Concatenate, then regroup
Collect the small partial tables in a list. After the loop, concatenate them and group again by the same keys, this time summing the partial values.
import pandas as pd
parts = []
with pd.read_csv("sales.csv", usecols=["region", "amount"], chunksize=200) as reader:
for chunk in reader:
parts.append(chunk.groupby("region")["amount"].agg(["sum", "count"]))
combined = pd.concat(parts).groupby(level=0).sum()
combined["mean"] = combined["sum"] / combined["count"]
print(combined)Here groupby(level=0) groups by the index, which holds the region names. This version is easy to read. Its cost is that the list holds one partial table per chunk. That is small when there are few groups, but with a million distinct keys and a hundred chunks you would hold up to a hundred million rows. In that case, merge as you go, or concatenate and regroup every few chunks to keep the list short.
Using different aggregations per column
Named aggregation lets you compute several statistics per group in one pass. The merge step then applies the matching rule to each column.
import pandas as pd
parts = []
with pd.read_csv("sales.csv", usecols=["region", "amount"], chunksize=200) as reader:
for chunk in reader:
parts.append(
chunk.groupby("region").agg(
total=("amount", "sum"),
n=("amount", "count"),
low=("amount", "min"),
high=("amount", "max"),
)
)
all_parts = pd.concat(parts)
result = all_parts.groupby(level=0).agg(
total=("total", "sum"),
n=("n", "sum"),
low=("low", "min"),
high=("high", "max"),
)
result["mean"] = result["total"] / result["n"]
print(result)Notice that the second agg is not the same as the first. The partial n column holds counts from each chunk, so the combined n is their sum, not a new count. Using count in the merge step would count the number of chunks that contained the group. This is a common source of wrong numbers, covered again in the pitfalls chapter.
Merge rules by statistic
| Statistic | Per-chunk partial | Merge rule | Final step |
|---|---|---|---|
| Sum | sum | add the sums | none |
| Count | count | add the counts | none |
| Mean | sum and count | add both | sum divided by count |
| Minimum | min | min of the minimums | none |
| Maximum | max | max of the maximums | none |
| Variance | count, sum, sum of squares | add all three | combine with a formula |
| Number of distinct values | set of values | union of the sets | size of the set |
| Median | not combinable | none exact | needs all values or an approximation |
The table shows the idea behind all combinable statistics: find partial values that you can merge with an associative operation, then derive the answer at the end. The mean is not combinable by itself, but the pair (sum, count) is.
Variance as an example
Variance can be rebuilt from the count n, the sum s, and the sum of squares q. The population variance is q / n - (s / n) ** 2.
import pandas as pd
parts = []
with pd.read_csv("sales.csv", usecols=["region", "amount"], chunksize=200) as reader:
for chunk in reader:
chunk = chunk.assign(square=chunk["amount"].astype("float64") ** 2)
parts.append(
chunk.groupby("region").agg(
n=("amount", "count"),
s=("amount", "sum"),
q=("square", "sum"),
)
)
stats = pd.concat(parts).groupby(level=0).sum()
stats["mean"] = stats["s"] / stats["n"]
stats["var"] = stats["q"] / stats["n"] - stats["mean"] ** 2
print(stats[["mean", "var"]])The cast to float64 before squaring avoids integer overflow if the column uses a small integer type. This formula can lose precision when the mean is large compared with the spread, because it subtracts two nearly equal numbers. For data like that, consider a pairwise update formula or a tool built for streaming statistics.
Distinct counts and exact sets
For the number of distinct values per group, store the set of values from each chunk, then union them. Memory grows with the number of distinct values, not with the number of rows, so this works until the distinct values themselves become large.
import pandas as pd
seen = {}
with pd.read_csv("sales.csv", usecols=["region", "amount"], chunksize=200) as reader:
for chunk in reader:
for region, values in chunk.groupby("region")["amount"]:
seen.setdefault(region, set()).update(values.unique())
print({region: len(values) for region, values in seen.items()})If the sets become too large, an approximate method such as HyperLogLog, or a different tool, is the usual answer. The final chapter lists such tools.
Edge cases
- Missing group keys.
groupbydrops rows whose key isNaNby default. Passdropna=Falseto keep them as their own group. Use the same setting in every chunk, and in the merge step, or the totals will not match. - Categorical keys. If the key column has a categorical dtype and you group with
observed=False, each partial table can include every category, including empty ones. This is harmless for sums but inflates the partial tables. Useobserved=Trueto keep them small. - Key dtype changes. If a key column looks numeric in one chunk and contains text in another, pandas may infer different dtypes per chunk. Then
1and"1"become separate groups after concatenation. Fix the key dtype inread_csvwithdtype={"region": "string"}or the type that fits your data. - Empty partial results. A filter applied before grouping can leave a chunk with no rows. The grouped result is then empty, and
addorconcathandles it correctly. Initializingtotals = Noneand testing for it, as in the first example, avoids special cases. - Multiple keys. Grouping by a list of columns produces a
MultiIndex.add,concatwithgroupby(level=[0, 1]), orgroupby(level=list(range(n)))all work the same way. Usegroupby(level=totals.index.names)if the names are set.
Choosing a merge strategy
| Situation | Suggested approach |
|---|---|
| Few groups, sums and counts only | Running table with `add(fill_value=0)` |
| Mixed statistics such as min, max and sum | Collect partial tables, then `concat` and `groupby(level=0)` with per-column rules |
| Many groups, many chunks | Merge as you go, or regroup every few chunks to limit the list size |
| Exact distinct counts | Dictionary of sets, if the distinct values fit in memory |
| Median, quantiles, mode on huge data | Approximate methods, or move to another tool |
Check your understanding
Exercise
A chunked job computes the average amount per region. Each chunk yields chunk.groupby("region")["amount"].mean(), and the job then averages those per-chunk means for each region. Explain why the result can be wrong, and describe the change needed to make it correct.
Show answer
Averaging per-chunk means gives every chunk the same weight, even when chunks contain different numbers of rows for a region. For example, chunk means of 10 (from 10 rows) and 20 (from 190 rows) average to 15, but the true mean is (100 + 3800) / 200 = 19.5. To fix it, compute sum and count per region in each chunk, add them across chunks, and divide the total sum by the total count at the end.
Exercise
You merge partial tables with pd.concat(parts).groupby(level=0).agg(n=("n", "count")), where each partial table has an n column of per-chunk row counts. What does the result contain, and what should the merge use instead?
Show answer
It counts how many partial tables contained each group, which equals the number of chunks in which the group appeared, not the number of rows. The merge should use sum on the n column so the per-chunk counts are added together.
Exercise
Why does totals.add(part, fill_value=0) work when a region first appears in a later chunk, while totals + part does not?
Show answer
The + operator aligns by index label and gives NaN for any label present in only one table, so the new region's values (and the running values of regions missing from part) become NaN. With fill_value=0, a missing label is treated as zero, so the value from the table that has it is kept.