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.
Python code
23 linesimport 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
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
- Use `csv.reader` with a separate header list instead of `DictReader`.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.