GroupBy
GroupBy Sum
Accumulate a running total per category by looping over paired category and
value lists. With pandas, df.groupby('cat')['val'].sum() splits the rows by
category, applies sum to the value column of each group, and combines the
results — the split-apply-combine pattern in one call.
By hand
With pandas
df.groupby('cat')['val'].sum() groups by category, selects the val column,
and sums each group. int() converts numpy scalars for a stable result dict.
naive.py
cats = ['a', 'b', 'a', 'c', 'b', 'a']
vals = [10, 20, 30, 40, 50, 60]
totals = {}
for cat, val in zip(cats, vals):
totals[cat] = totals.get(cat, 0) + val
result = {k: totals[k] for k in sorted(totals)}
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
cats = ['a', 'b', 'a', 'c', 'b', 'a']
vals = [10, 20, 30, 40, 50, 60]
df = pd.DataFrame({'cat': cats, 'val': vals})
sums = df.groupby('cat')['val'].sum()
result = {k: int(sums[k]) for k in sorted(sums.index)}
print('index:', sorted(sums.index.tolist()))
print('values:', [int(sums[k]) for k in sorted(sums.index)])
print('dtype:', sums.dtype)
print('RESULT:', result)
index: ['a', 'b', 'c']
values: [100, 70, 40]
dtype: int64
RESULT: {'a': 100, 'b': 70, 'c': 40}
Implementation notes
groupby('cat')['val']selects a single column from the grouped object before aggregating. Without the column selection,.sum()would sum every numeric column in the DataFrame.- The three-step pattern —
groupby(split) → column select → aggregation (apply) → result Series (combine) — is the core of split-apply-combine and applies to all aggregations:sum,mean,min,max,std. - Cross-reference:
group-sum(python-data-basics) for the pure-Python accumulator version;groupby-mean(this chapter) for the mean variant.