import csv from collections import defaultdict from html import escape from statistics import median rows = list(csv.DictReader(open('titanic.csv', encoding='utf-8-sig'))) print(f'[1/4] loaded {len(rows)} Titanic records', flush=True) ages = [float(r['age']) for r in rows if r.get('age')] median_age = median(ages) if ages else 30 for r in rows: r['age'] = r.get('age') or str(median_age) r['deck'] = r.get('deck') or 'Unknown' r['embarked'] = r.get('embarked') or 'S' r['class'] = r.get('class') or r.get('pclass', '') sibsp = int(float(r.get('sibsp') or 0)) parch = int(float(r.get('parch') or 0)) r['is_alone'] = 'true' if sibsp + parch == 0 else 'false' # bucket age into an ordered category column (pandas-style astype('category')) age_val = float(r['age']) r['age_category'] = 'child' if age_val < 18 else ('senior' if age_val >= 60 else 'adult') print('[2/4] filled age/deck and derived is_alone', flush=True) # encode categorical columns into integer category codes (equivalent to # df[col].astype('category').cat.codes) for downstream modelling category_cols = ['sex', 'embarked', 'class', 'deck', 'age_category'] for col in category_cols: levels = sorted({(r.get(col) or '') for r in rows}) codes = {level: idx for idx, level in enumerate(levels)} for r in rows: r[col + '_code'] = str(codes[r.get(col) or '']) print('[3/4] encoded embarked/class categorical values', flush=True) extra = ['age', 'deck', 'embarked', 'class', 'is_alone', 'age_category'] + [c + '_code' for c in category_cols] fields = list(dict.fromkeys(list(rows[0].keys()) + extra)) with open('titanic_clean.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=fields) writer.writeheader() writer.writerows(rows) groups = defaultdict(lambda: [0, 0]) for row in rows: survived = str(row.get('survived', '')).strip().lower() in {'1', 'true'} for field in ('sex', 'class'): counts = groups[(field, row[field])] counts[0] += int(survived) counts[1] += 1 table_rows = [] bars = [] for index, ((field, category), (survived, total)) in enumerate(sorted(groups.items())): rate = survived / total safe_field, safe_category = escape(field), escape(category) table_rows.append( f'' f'{safe_field}{safe_category}{survived}' f'{total}{rate:.1%}' ) y = 16 + index * 38 bars.append( f'{safe_field}: {safe_category}' f'' ) height = 32 + len(groups) * 38 report = ( 'Titanic survival analysis' '' '

Titanic survival analysis

' f'

Cleaned {len(rows)} records. Missing ages use the observed median; missing deck is Unknown.

' '

Survival rates by sex and class

' '' '' + ''.join(table_rows) + '
GroupCategorySurvivedTotalRate
' f'' + ''.join(bars) + '
' ) with open('report.html', 'w', encoding='utf-8') as handle: handle.write(report) print('[4/4] wrote titanic_clean.csv and report.html', flush=True)