File size: 2,102 Bytes
0f43b03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "# 年龄分箱:按十岁一段,与之前保持一致\n",
    "def age_decade(a):\n",
    "    if a is None:\n",
    "        return None\n",
    "    lo = (a // 10) * 10\n",
    "    return f\"{lo}-{lo+9}\"\n",
    "\n",
    "# (age_group, sex) -> count\n",
    "agesex = defaultdict(int)\n",
    "age_order = []                       # 保持出现顺序里有效的箱\n",
    "for item in items:                   # items = 去重后的记录\n",
    "    a = get_age(item)\n",
    "    s = get_sex(item)                # \"Male\" / \"Female\" / \"Unknown\"\n",
    "    grp = age_decade(a)\n",
    "    if grp is None or s not in (\"Male\", \"Female\"):\n",
    "        continue                     # 年龄或性别缺失的跳过(也可单列统计)\n",
    "    agesex[(grp, s)] += 1\n",
    "\n",
    "# 整理成有序表\n",
    "all_groups = sorted({g for (g, _) in agesex}, key=lambda x: int(x.split(\"-\")[0]))\n",
    "\n",
    "print(f\"{'Age_Group':10s} {'Male':>8s} {'Female':>8s} {'Total':>8s}\")\n",
    "print(\"-\" * 38)\n",
    "tot_m = tot_f = 0\n",
    "for g in all_groups:\n",
    "    m = agesex[(g, \"Male\")]\n",
    "    f = agesex[(g, \"Female\")]\n",
    "    tot_m += m\n",
    "    tot_f += f\n",
    "    print(f\"{g:10s} {m:8d} {f:8d} {m+f:8d}\")\n",
    "print(\"-\" * 38)\n",
    "print(f\"{'TOTAL':10s} {tot_m:8d} {tot_f:8d} {tot_m+tot_f:8d}\")\n",
    "\n",
    "# ---- 直接可粘贴回来的字面量(把这段输出发我,我把精确数字填进 PPTX) ----\n",
    "print(\"\\n# copy below\")\n",
    "print(\"age_male   =\", [agesex[(g, 'Male')]   for g in all_groups])\n",
    "print(\"age_female =\", [agesex[(g, 'Female')] for g in all_groups])\n",
    "print(\"age_labels =\", all_groups)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}