thecodex.expert · The Codex Family of Knowledge
Tier 2 · Intermediate · Python Project

CSV Data Analyser

Load a real CSV dataset and produce insights — averages, totals, and the biggest values. The most in-demand skill in programming.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want a tool that reads a CSV file (the universal spreadsheet format) and answers real questions about it: how many rows, the average of a column, the largest value, totals per group. It teaches loading structured data and analysing it — the core of data science and analytics.

Where this shows up: business dashboards, sales reports, scientific analysis, machine-learning data prep, any decision backed by numbers. “Load data, compute insight” is one of the most valuable skills you can have.

2 How to Think About It

Think about the steps from file to insight, before any code:

The plan — in plain English
1. Read the CSV file into rows. → 2. Each row becomes a dictionary keyed by the column headers. → 3. To analyse a column, pull out its values and compute — count, sum, average, max. → 4. Show the insights.

Open CSV file

Read header row

Read each row as a dict

Pull out a column's values

Count, sum, average, max

Show insights

3 The Build — explained part by part

Here is the complete analyser. Each part is explained below.

Pythonanalyse.py
import csv

def load_csv(filename):
    # DictReader turns each row into a dictionary keyed by the header names.
    with open(filename) as f:
        return list(csv.DictReader(f))

def column_values(rows, column):
    # Pull out one column's values, converted to numbers.
    return [float(row[column]) for row in rows]

def analyse(rows, column):
    values = column_values(rows, column)
    return {
        "count": len(values),
        "total": sum(values),
        "average": sum(values) / len(values),
        "max": max(values),
        "min": min(values),
    }

if __name__ == "__main__":
    rows = load_csv("data.csv")
    print(f"Rows: {len(rows)}")
    stats = analyse(rows, "price")
    for key, value in stats.items():
        print(f"{key}: {value:.2f}")
What each part does — in plain words
import csv — Python’s built-in CSV reader, which handles all the tricky details (commas inside quotes, etc.) for you.

csv.DictReader(f) — the key tool: it reads the header row, then turns every following row into a dictionary keyed by those headers. So row["price"] gives that row’s price.

column_values(rows, column) — pull one column’s values out of every row, converting each to a number with float (CSV values arrive as text).

analyse(rows, column) — compute the insights using built-ins: len (count), sum (total), sum/len (average), max and min.

the for loop at the end — print each statistic neatly, formatted to two decimals.
Common mistakes — and how to avoid them
✗ Forgetting float() — CSV values are text, so sum tries to add strings and fails.
✓ Convert each value to a number with float() before computing.
✗ Using csv.reader instead of DictReader — then you reference columns by fragile number, not name.
✓ Use DictReader so you access columns by header name.
✗ Dividing by zero on an empty file — average crashes.
✓ Check there is at least one row before averaging.

4 Test & Prove Each Part

We test the analysis on a small set of known numbers, so we can check every statistic by hand.

The count matches the number of rows
The average is computed correctly
Max and min find the right values
Pythontest_analyse.py
from analyse import analyse


ROWS = [
    {"price": "10"},
    {"price": "20"},
    {"price": "30"},
]


def test_count():
    """Three rows give a count of 3."""
    assert analyse(ROWS, "price")["count"] == 3


def test_average():
    """10, 20, 30 average to 20."""
    assert analyse(ROWS, "price")["average"] == 20


def test_max_and_min():
    """Max is 30, min is 10."""
    stats = analyse(ROWS, "price")
    assert stats["max"] == 30
    assert stats["min"] == 10

Run with pytest -v. We feed analyse a tiny known dataset so every number can be verified by hand. Testing analytics against hand-checkable data is how you trust the results on real data.

5 The Interface

INPUTCSV filea file with a header row
What it expects
name,price
Apple,1.20
Bread,2.50
OUTPUTstatisticscount, total, average, max, min
What it returns
Rows: 2
count: 2.00
average: 1.85
max: 2.50

6 Run It & Automate It

Run it locally
python3 analyse.py
Point it at a data.csv file with a numeric column and see the insights.

Jenkins runs the tests automatically — each line explained below.

What you should see when it works
Terminala real run
Rows: 100
count: 100.00
total: 4521.50
average: 45.22
max: 199.99
min: 0.99
If it breaks — how to fix it
🚨 ValueError: could not convert string to float.
That column has non-numeric values (or a stray header). Make sure you analyse a numeric column.
🚨 KeyError.
The column name does not match a header exactly — check spelling and capitalisation.
GroovyJenkinsfile
// Jenkinsfile — automated tests on every change.
pipeline {
    agent any
    stages {
        stage('Get the code') { steps { checkout scm } }       // download the code
        stage('Install') { steps { sh 'python3 -m venv venv && . venv/bin/activate && pip install pytest' } }  // test tool
        stage('Test') { steps { sh '. venv/bin/activate && pytest -v' } }   // run every test
    }
    post {
        success { echo 'All tests passed.' }
        failure { echo 'A test failed — look above.' }
    }
}
🎯 Try this next — make it yours
  1. Group and total. Sum a column per category (sales per region). (Teaches: grouping.)
  2. Filter rows. Analyse only rows matching a condition. (Teaches: filtering.)
  3. Export a report. Write the insights to a new file. (Teaches: writing output.)
What you learned
You learned to load structured data from a CSV with DictReader, extract a column, and compute insights with built-ins. This load-then-analyse pattern is the heart of all data work. Related: csv, Comprehensions.