How to Sum a CSV Column by Group in Python

This code reads a CSV string and sums a specified column for each unique value of a group key using the csv module and defaultdict.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

23 lines
Python 3.9+
import csv
from collections import defaultdict
from io import StringIO

def aggregate_csv(csv_data, group_key, sum_column):
    totals = defaultdict(float)
    reader = csv.DictReader(StringIO(csv_data))
    for row in reader:
        key = row[group_key]
        totals[key] += float(row[sum_column])
    return dict(totals)

if __name__ == "__main__":
    data = """department,employee,salary
Engineering,Alice,75000
Sales,Bob,60000
Engineering,Carol,82000
Sales,Dave,55000
Marketing,Eve,70000
"""
    result = aggregate_csv(data, "department", "salary")
    for dept, total in sorted(result.items()):
        print(f"{dept}: {total}")

Output

stdout
Engineering: 157000.0
Marketing: 70000.0
Sales: 115000.0

How it works

The csv.DictReader reads each row as a dictionary keyed by the header row. A defaultdict(float) is used to accumulate totals without checking key existence. The float() conversion handles salary values as decimals. The sorted() call ensures deterministic output order. This pattern scales well for moderately sized CSVs in memory.

Common mistakes

  • Forgetting to convert the sum column to a numeric type like `float`.
  • Assuming input is a file path instead of a string; the code uses `StringIO` for text.
  • Not handling missing or empty group key columns gracefully.
  • Using a regular dict and getting KeyError when a new group appears.

Variations

  1. Use `csv.reader` with a separate header list instead of `DictReader`.
  2. Load from an actual file with `open` and pass the file object directly to `csv.DictReader`.

Real-world use cases

  • Computing total sales per region from a daily transaction CSV export.
  • Summing expenses by category in a budget tracking script.
  • Aggregating time-tracking data by project for reporting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.