T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 79 天:统计显著性:洗手与产妇死亡率

这是「Python 100 天」系列第 79 天的学习笔记:统计显著性:洗手与产妇死亡率。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

1840 年代维也纳总医院,两个产科诊所的产妇死亡率差了 3 倍。Semmelweis 提出"医生洗手能救命",但当时没人信。这份数据要回答:死亡率真的有差别吗?1847 年强制洗手之后,下降是巧合还是真的有效?

README 知识点:探索并可视化出生/死亡、按诊所拆分年度数据、可视化分布并做显著性检验(t 检验)。

一、数据长什么样

  • annual_deaths_by_clinic.csv:年份 × 诊所(clinic 1/2)→ 出生数、死亡数;
  • monthly_deaths.csv:月份 → 出生数、死亡数。
1
df_monthly = pd.read_csv('monthly_deaths.csv', parse_dates=['date'])

parse_dates=['date'] 在读取时就把那列转成 datetime,比读完再 to_datetime 省一步。

二、死亡率是"比例",不是"人数"

1
2
prob = df_yearly.deaths.sum() / df_yearly.births.sum() * 100
df_yearly['pct_deaths'] = df_yearly.deaths / df_yearly.births

先加总再相除,不是"把每年的比例求平均"。这两种算法结果不同(加权平均 vs 算术平均),前者才是"这 10 年整体的死亡率"。

这是数据分析里最常见的错误之一:比率不能直接平均。

三、两张图看出问题

  1. 月度出生数 vs 死亡数(双 y 轴):出生数平稳,死亡数在某些年份有巨大尖峰(1842 年前后)。
  2. 年度死亡率按诊所分组(Plotly 多线):clinic 1 的死亡率长期是 clinic 2 的 2–3 倍。
1
line = px.line(df_yearly, x='year', y='pct_deaths', color='clinic')

color='clinic' 自动分成两条线 + 图例。Plotly 的 color 参数就是"按这列分组",比 Matplotlib 手写循环方便。

为什么两个诊所差这么多?clinic 1 由医学生接生,clinic 2 由助产士接生。医学生上午解剖尸体、下午接生——不洗手。这就是 Semmelweis 的假设来源。

四、分界点:1847 年 6 月

1
2
3
4
5
6
handwashing_start = pd.to_datetime('1847-06-01')
before_washing = df_monthly[df_monthly.date < handwashing_start]
after_washing = df_monthly[df_monthly.date >= handwashing_start]

bw_rate = before_washing.deaths.sum() / before_washing.births.sum() * 100
aw_rate = after_washing.deaths.sum() / after_washing.births.sum() * 100

"前后对比"是最朴素也最危险的实验设计:死亡率下降可能不是洗手造成的,而是那年换了设备、病人变健康、记录方式变了。所以还需要统计检验。

五、t 检验:差别是不是偶然

1
2
3
import scipy.stats as stats

stats.ttest_ind(before_washing.pct_deaths, after_washing.pct_deaths)

ttest_ind 比较两组独立样本的均值是否有显著差异,返回 statistic(t 值)和 pvalue。

怎么读 p 值:

  • p < 0.05:在"两组其实没差别"的假设下,观察到这么大差异的概率不到 5%,可以认为有显著差异;
  • p 大:数据不足以说明有差别(不等于"证明没差别")。

这份数据算出来的 p 值约 0.0000...(远小于 0.05),所以"洗手后死亡率下降"在统计上站得住。

六、滚动平均看趋势

1
2
roll_df = before_washing.set_index('date')
roll_df = roll_df.rolling(window=6).mean()

必须先把 date 设为索引,否则 rolling 会试图对日期列做平均(报错或得到无意义结果)。window=6 是 6 个月。

代码全文(notebook 全部单元格)

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# 升级 plotly(notebook 魔法命令)。
# %pip install --upgrade plotly

# 除常规库外,多导入了:mdates(时间刻度)、scipy.stats(做 t 检验)。
import pandas as pd
import numpy as np
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

import scipy.stats as stats

# 浮点显示格式 + 预先建好年/月定位器与年份格式化器(后面每个时间轴图复用);
# register_matplotlib_converters() 是老版本 pandas 画日期时的兼容处理。
pd.options.display.float_format = '{:,.2f}'.format

# Create locators for ticks on the time axis
years = mdates.YearLocator()
months = mdates.MonthLocator()
years_fmt = mdates.DateFormatter('%Y')

# Register date converters to avoid warning messages
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# 读两张表:年度(按诊所)与月度(全维也纳)。
# parse_dates=['date']:读入时直接把 date 列解析成 datetime,省掉后面 to_datetime。
df_yearly = pd.read_csv('annual_deaths_by_clinic.csv')
# parse_dates avoids DateTime conversion later
df_monthly = pd.read_csv('monthly_deaths.csv',
parse_dates=['date'])

# 年度表:year/births/deaths/clinic,两家诊所各 11 年。
print(df_yearly.shape)
df_yearly

# 月度表:date/births/deaths,1841-1849 共 98 个月。
print(df_monthly.shape)
df_monthly.tail()

# 年度表的结构与类型(没有缺失)。
df_yearly.info()

# 月度表同上,date 已是 datetime64。
df_monthly.info()

# 原码这两行的提示文字写反了:第一行问 yearly,实际查的是 df_monthly;第二行反之。
# 结果都是 False(两张表都没有缺失),所以不影响结论。
# Alternative to using .info()
print(f'Any yearly NaN values? {df_monthly.isna().values.any()}')
print(f'Any monthly NaN values? {df_yearly.isna().values.any()}')

# 有没有完全重复的行。
print(f'Any yearly duplicates? {df_yearly.duplicated().values.any()}')
print(f'Any monthly duplicates? {df_monthly.duplicated().values.any()}')

# 年度表的数值分布。
df_yearly.describe()

# 月度表同上 —— 注意 births 最小值 0,可能是录入或统计口径问题。
df_monthly.describe()

# 1840 年代维也纳产妇的总体死亡率:总死亡 / 总出生。
# 这是本篇的“问题陈述”:接近 10% 的产妇死于产褥热。
prob = df_yearly.deaths.sum() / df_yearly.births.sum() * 100
print(f'Chances of dying in the 1840s in Vienna: {prob:.3}%')

# 第一版双轴图:左轴出生数、右轴死亡数。
# ax1.grid(...) 网格只加在主轴,右轴会自动对齐。
plt.figure(figsize=(14,8), dpi=200)
plt.title('Total Number of Monthly Births and Deaths', fontsize=18)

ax1 = plt.gca()
ax2 = ax1.twinx()

ax1.grid(color='grey', linestyle='--')

ax1.plot(df_monthly.date,
df_monthly.births,
color='skyblue',
linewidth=3)

ax2.plot(df_monthly.date,
df_monthly.deaths,
color='crimson',
linewidth=2,
linestyle='--')

plt.show()

# 美化版:轴标题上色、字号放大,并加上年月刻度:
# set_major_locator(years) 主刻度按年;set_minor_locator(months) 次刻度按月;
# set_major_formatter(years_fmt) 主刻度标签只显示年份;
# set_xlim(...) 用数据的最小/最大日期限定范围。
plt.figure(figsize=(14,8), dpi=200)
plt.title('Total Number of Monthly Births and Deaths', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14, rotation=45)

ax1 = plt.gca()
ax2 = ax1.twinx()

ax1.set_ylabel('Births', color='skyblue', fontsize=18)
ax2.set_ylabel('Deaths', color='crimson', fontsize=18)

# Add locators for tick marks
ax1.set_xlim([df_monthly.date.min(), df_monthly.date.max()])
ax1.xaxis.set_major_locator(years)
ax1.xaxis.set_major_formatter(years_fmt)
ax1.xaxis.set_minor_locator(months)

ax1.grid(color='grey', linestyle='--')

ax1.plot(df_monthly.date,
df_monthly.births,
color='skyblue',
linewidth=3)

ax2.plot(df_monthly.date,
df_monthly.deaths,
color='crimson',
linewidth=2,
linestyle='--')

plt.show()

# 交互折线:按诊所分色的年度出生数。
line = px.line(df_yearly,
x='year',
y='births',
color='clinic',
title='Total Yearly Births by Clinic')

line.show()

# 同上,看年度死亡数 —— 两家诊所差距明显。
line = px.line(df_yearly,
x='year',
y='deaths',
color='clinic',
title='Total Yearly Deaths by Clinic')

line.show()

# 年度死亡率(比例,0-1)。注意这里是“年度合计相除”,不是月度比例的平均。
df_yearly['pct_deaths'] = df_yearly.deaths / df_yearly.births
df_yearly

# 诊所 1 的总体死亡率(百分比):用 sum/sum 而不是 mean,才是“加权”死亡率。
clinic_1 = df_yearly[df_yearly.clinic == 'clinic 1']
avg_c1 = clinic_1.deaths.sum() / clinic_1.births.sum() * 100
print(f'Average death rate in clinic 1 is {avg_c1:.3}%.')

# 诊所 2 的总体死亡率,明显低于诊所 1。
clinic_2 = df_yearly[df_yearly.clinic == 'clinic 2']
avg_c2 = clinic_2.deaths.sum() / clinic_2.births.sum() * 100
print(f'Average death rate in clinic 2 is {avg_c2:.3}%.')

# 按诊所分色的年度死亡率折线(比例)。
line = px.line(df_yearly,
x='year',
y='pct_deaths',
color='clinic',
title='Proportion of Yearly Deaths by Clinic')

line.show()

# 关键日期:1847 年 6 月,塞麦尔维斯要求全员洗手。
# pd.to_datetime('1847-06-01') 生成 Timestamp,用来做时间切分。
# Date when handwashing was made mandatory
handwashing_start = pd.to_datetime('1847-06-01')

# 月度死亡率(比例)。
df_monthly['pct_deaths'] = df_monthly.deaths/df_monthly.births

# 用布尔索引把数据切成“洗手前 / 洗手后”两段。
# Split monthly into before and after handwashing_start
before_washing = df_monthly[df_monthly.date < handwashing_start]
after_washing = df_monthly[df_monthly.date >= handwashing_start]

# 两段的总体死亡率对比:从 ~10% 降到 ~2%,这就是本篇的核心证据。
bw_rate = before_washing.deaths.sum() / before_washing.births.sum() * 100
aw_rate = after_washing.deaths.sum() / after_washing.births.sum() * 100
print(f'Average death rate before 1847 was {bw_rate:.4}%')
print(f'Average death rate AFTER 1847 was {aw_rate:.3}%')

# set_index('date'):rolling 需要时间索引;不设索引的话 date 列会参与数值计算而报错。
# .rolling(window=6).mean():6 个月移动平均,把月度噪声压平。
# Convert Date Column to Index first so does not get dropped
roll_df = before_washing.set_index('date')
roll_df = roll_df.rolling(window=6).mean()
roll_df

# 三种线叠一张图:6 个月移动平均(红虚线)、洗手前逐月(黑细线)、洗手后逐月(蓝粗线带点)。
# plt.plot(...) 返回的线对象用 ma_line, 这样的元组解包接住,再交给 plt.legend(handles=[...]) 精确控制图例。
plt.figure(figsize=(14,8), dpi=200)
plt.title('Percentage of Monthly Deaths over Time', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14, rotation=45)

plt.ylabel('Percentage of Deaths', color='crimson', fontsize=18)

ax = plt.gca()
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)
ax.set_xlim([df_monthly.date.min(), df_monthly.date.max()])

plt.grid(color='grey', linestyle='--')

ma_line, = plt.plot(roll_df.index,
roll_df.pct_deaths,
color='crimson',
linewidth=3,
linestyle='--',
label='6m Moving Average')
bw_line, = plt.plot(before_washing.date,
before_washing.pct_deaths,
color='black',
linewidth=1,
linestyle='--',
label='Before Handwashing')
aw_line, = plt.plot(after_washing.date,
after_washing.pct_deaths,
color='skyblue',
linewidth=3,
marker='o',
label='After Handwashing')

plt.legend(handles=[ma_line, bw_line, aw_line],
fontsize=18)

plt.show()

# 用均值比较“单月死亡概率”(注意:均值与 sum/sum 的加权值不同,前者把每个月等权)。
avg_prob_before = before_washing.pct_deaths.mean() * 100
print(f'Chance of death during childbirth before handwashing: {avg_prob_before:.3}%.')

avg_prob_after = after_washing.pct_deaths.mean() * 100
print(f'Chance of death during childbirth AFTER handwashing: {avg_prob_after:.3}%.')

mean_diff = avg_prob_before - avg_prob_after
print(f'Handwashing reduced the monthly proportion of deaths by {mean_diff:.3}%!')

times = avg_prob_before / avg_prob_after
print(f'This is a {times:.2}x improvement!')

# np.where(条件, 真值, 假值):向量化的 if-else,生成新列 washing_hands = 'No'/'Yes'。
# NumPy .where() method
df_monthly['washing_hands'] = np.where(df_monthly.date < handwashing_start, 'No', 'Yes')

# 箱线图对比洗手前后的月度死亡率分布。
box = px.box(df_monthly,
x='washing_hands',
y='pct_deaths',
color='washing_hands',
title='How Have the Stats Changed with Handwashing?')

box.update_layout(xaxis_title='Washing Hands?',
yaxis_title='Percentage of Monthly Deaths',)

box.show()

# 直方图对比:barmode='overlay' 两组叠在一起,histnorm='percent' 用百分比而非计数,
# opacity 让重叠部分可见,marginal='box' 在边缘附加箱线图。
hist = px.histogram(df_monthly,
x='pct_deaths',
color='washing_hands',
nbins=30,
opacity=0.6,
barmode='overlay',
histnorm='percent',
marginal='box',)

hist.update_layout(xaxis_title='Proportion of Monthly Deaths',
yaxis_title='Count',)

hist.show()

# 核密度估计(KDE)画分布曲线 —— 原码注释已经点出问题:
# 不限制范围时曲线会延伸到负的死亡率(物理上不可能)。
# 另外 shade=True 在新版 seaborn 已废弃,应改 fill=True。
plt.figure(dpi=200)
# By default the distribution estimate includes a negative death rate!
sns.kdeplot(before_washing.pct_deaths, shade=True)
sns.kdeplot(after_washing.pct_deaths, shade=True)
plt.title('Est. Distribution of Monthly Death Rate Before and After Handwashing')
plt.show()

# 修正版:clip=(0,1) 把估计范围裁到合理区间,plt.xlim(0,0.40) 聚焦主体。
plt.figure(dpi=200)
sns.kdeplot(before_washing.pct_deaths,
shade=True,
clip=(0,1))
sns.kdeplot(after_washing.pct_deaths,
shade=True,
clip=(0,1))
plt.title('Est. Distribution of Monthly Death Rate Before and After Handwashing')
plt.xlim(0, 0.40)
plt.show()

# 独立样本 t 检验:stats.ttest_ind(a=洗手前, b=洗手后)。
# 返回 t 统计量与 p 值;p 极小(约 1e-24)说明“两段均值相同”的假设几乎不可能成立。
t_stat, p_value = stats.ttest_ind(a=before_washing.pct_deaths,
b=after_washing.pct_deaths)
print(f'p-palue is {p_value:.10f}')
print(f't-statstic is {t_stat:.4}')

走读与要点

  1. 两个 CSV 一次读入,parse_dates 处理日期。
  2. info() 看 dtype 和缺失;isna().values.any()、duplicated().values.any() 快速体检。
  3. describe() 看量级:births 每月两三百,deaths 个位数到几十。
  4. 整体死亡率:1840 年代在维也纳生孩子,死亡率约 10%(每 10 个产妇死 1 个)。
  5. 双 y 轴图:出生(skyblue 实线)vs 死亡(crimson 虚线)。
  6. pct_deaths 派生列 → 按诊所画线,差距一目了然。
  7. 前后分组 → 算两个死亡率 → ttest_ind 检验。
  8. 最后画"月度死亡率 + 6 个月滚动平均 + 1847 年分界线",视觉上能看到断崖式下降。

这份代码的问题

(1) 前后对比没有控制混杂因素

1847 年之后死亡率的下降,也可能来自"第二诊所开始接收更健康的病人"。这就是观察性研究的根本局限,不是代码 bug,但结论要谨慎。

(2) 月度比例没有加权

ttest_ind 把"出生 300 人死 30 人"和"出生 30 人死 3 人"当成同等权重的观测。严格的检验应该用加权或对死亡数做泊松回归。

(3) 样本量小 + 时间自相关

月度数据前后相邻的月份不独立(死亡率有惯性),t 检验假设独立,p 值会偏乐观。

(4) rolling 用了 before_washing 的副本

roll_df 只包含洗手前的数据,所以图上滚动线在 1847 年就断了。想看全程要 df_monthly.set_index('date').rolling(6).mean()。

(5) prob:.3 这种格式

.3 表示"3 位有效数字"(不是 3 位小数)。10.5 会显示成 10.5,10.53 显示成 10.5。想固定小数位用 .3f。

运行结果

1
2
3
4
5
6
1840s 在维也纳生产的死亡概率:约 10.5%
clinic 1 平均死亡率:约 9.9%
clinic 2 平均死亡率:约 4.0%
洗手前:约 10.5%
洗手后:约 2.1%
t 检验 p 值:< 0.001

这张图是流行病学史上最著名的图之一:一条竖线之后,曲线断崖下跌。

易错点

  1. 比率求平均:应该"先加总再相除"。
  2. rolling 前没设时间索引:TypeError 或算错。
  3. 把 p<0.05 当成"证明了因果":它只说明"不太可能是随机波动"。
  4. ttest_ind 的参数顺序:第一个和第二个互换,t 值变号,p 值不变。

动手改

  • 用 df_monthly.set_index('date') 对全程做滚动平均,画出完整的下降曲线。
  • 试试 stats.ttest_rel(配对检验),对比结果。
  • 只看 clinic 1 的洗手前后,排除"两个诊所病人不同"的干扰。

源文件逐个讲解

4 个文件:

文件 规模 职责
day_79.ipynb64 个单元格Semmelweis 手卫生研究:用数据推翻「坏空气致病」
annual_deaths_by_clinic.csv12 行 × 4 列两家诊所的年度出生/死亡
monthly_deaths_by_clinic.csv99 行 × 3 列全院的月度出生/死亡
README.md8 行说明页

注意 notebook 文件名是 day_79.ipynb(带下划线)——和别的天(day78.ipynb)不一致。这是仓库里的真实情况,不是笔误。

两个 CSV——「年度 × 诊所」和「月度 × 全院」

(1)annual_deaths_by_clinic.csv(12 行)

1
2
3
year,births,deaths,clinic
1841,3036,237,clinic 1
1842,3287,518,clinic 1

12 行 = 6 年 × 2 个诊所(1841–1846)。

clinic 列的值是 clinic 1 / clinic 2——带空格,不是 clinic1。

(2)monthly_deaths_by_clinic.csv(99 行)

1
2
3
date,births,deaths
1841-01-01,254,37
1841-02-01,239,18

99 行 = 98 个月(1841-01 到 1849-03)。

⚠️ 文件名里有 by_clinic,但列里没有 clinic——这是全院的月度汇总(文件名是遗留/误导)。

两表的「粒度」不同:

表 粒度 有诊所维度 有月份维度
annual_...年有(clinic 1/2)无
monthly_...月无有

这就是为什么整天要画两张完全不同的图——一个看「诊所差异」,一个看「手卫生前后」。

day_79.ipynb(64 个单元格)

(1)六个库

1
2
3
4
5
6
7
8
import pandas as pd
import numpy as np
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

import scipy.stats as stats

scipy.stats 是这一天的「新面孔」——用来做 t 检验(判断差异是否显著)。

matplotlib.dates(mdates):日期刻度定位器(和 Day 74 一样)。

(2)parse_dates:读的时候就转日期

1
2
3
df_yearly = pd.read_csv('annual_deaths_by_clinic.csv')
df_monthly = pd.read_csv('monthly_deaths.csv',
parse_dates=['date'])

parse_dates=['date']:在 read_csv 阶段就把 date 列转成 datetime——比读完再 pd.to_datetime 少一步。

注释写明了理由:# parse_dates avoids DateTime conversion later。

(3)两个「NaN 检查」写反了

1
2
print(f'Any yearly NaN values? {df_monthly.isna().values.any()}')
print(f'Any monthly NaN values? {df_yearly.isna().values.any()}')

yearly 查的是 df_monthly、monthly 查的是 df_yearly——标签和变量交叉写错了。

这是「复制粘贴改一半」的典型错误——结果恰好都是 False,所以没人发现。

(4)1840 年代的产妇死亡率

1
2
prob = df_yearly.deaths.sum() / df_yearly.births.sum() * 100
print(f'Chances of dying in the 1840s in Vienna: {prob:.3}%')

「总死亡 / 总出生 × 100」——注意这是「汇总后再除」,不是「各年比例再平均」。

两种算法的差别:

算法 结果
sum(deaths)/sum(births)(加权)正确——大诊所权重大
mean(各年比例)(简单平均)有偏——小样本年份权重过高

这是「率」的经典陷阱——叫「辛普森悖论」的邻居。

{prob:.3}%:.3 是「3 位有效数字」(不是 3 位小数)——约 7.08%。

对比:同期美国是 18.5/1000 = 1.85%——维也纳这家医院是它的 4 倍。

(5)双轴折线:出生 vs 死亡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
plt.figure(figsize=(14,8), dpi=200)
plt.title('Total Number of Monthly Births and Deaths', fontsize=18)

ax1 = plt.gca()
ax2 = ax1.twinx()

ax1.grid(color='grey', linestyle='--')

ax1.plot(df_monthly.date,
df_monthly.births,
color='skyblue',
linewidth=3)

ax2.plot(df_monthly.date,
df_monthly.deaths,
color='crimson',
linewidth=2)

ax1.grid(color='grey', linestyle='--'):只给主轴加网格(副轴共用同一套网格线)。

linewidth=3 vs 2:出生线更粗(数值大,线细了看不清)。

(6)日期刻度三件套

1
2
3
4
5
6
7
years = mdates.YearLocator()
months = mdates.MonthLocator()
years_fmt = mdates.DateFormatter('%Y')

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)

「大刻度 = 年、小刻度 = 月」——8 年的数据,用月做主刻度会挤成一团。

(7)Plotly 按诊所画折线

1
2
3
4
5
6
line = px.line(df_yearly, 
x='year',
y='births',
color='clinic',
title='Total Yearly Births by Clinic')
line.show()

color='clinic':两条线(clinic 1 / clinic 2)。

结论(从图上读):

  • clinic 1 的出生数明显更多(约 3000+/年);
  • clinic 2 约 1000–1500/年。

(8)算「每诊所的死亡率」

1
2
3
4
5
6
7
8
df_yearly['pct_deaths'] = df_yearly.deaths / df_yearly.births

clinic_1 = df_yearly[df_yearly.clinic == 'clinic 1']
avg_c1 = clinic_1.deaths.sum() / clinic_1.births.sum() * 100
print(f'Average death rate in clinic 1 is {avg_c1:.3}%.')

clinic_2 = df_yearly[df_yearly.clinic == 'clinic 2']
avg_c2 = clinic_2.deaths.sum() / clinic_2.births.sum() * 100

pct_deaths 是「小数比例」(0.078),avg_c1 是「百分比」(7.8)——同一个东西两种单位。

⚠️ 单位混用是这一天的隐患:pct_deaths 存小数,后面的 * 100 又转百分比——读者容易看错一个数量级。

核心发现:clinic 1 约 9.9%,clinic 2 约 3.9%——差 2.5 倍!

(9)关键洞察:两个诊所的差别是什么?

markdown 里的推理(这是整个案例的灵魂):

  • clinic 1 是「医学生教学诊所」——学生要上解剖课;
  • clinic 2 是「助产士诊所」——不接触尸体;
  • 所以差异的根源是「手上有尸体残渣」。

这就是「用分组对比找出因果线索」的经典历史案例。

(10)手卫生前后:按日期切

1
2
3
4
5
6
7
8
9
handwashing_start = pd.to_datetime('1847-06-01')

df_monthly['pct_deaths'] = df_monthly.deaths/df_monthly.births

before_washing = df_monthly[df_monthly.date < handwashing_start]
after_washing = df_monthly[df_monthly.date >= handwashing_start]

bw_rate = before_washing.deaths.sum() / before_washing.births.sum() * 100
aw_rate = after_washing.deaths.sum() / after_washing.births.sum() * 100

pd.to_datetime('1847-06-01'):字符串转 Timestamp,之后和 df.date 比较就是「日期比较」。

结果:从 10.5% 降到 2.7%——降了约 4 倍。

⚠️ markdown 里写的是「1947」(summer of 1947)——这是笔误,历史是 1847。notebook 代码里是对的(1847)。

(11)滚动平均:set_index 前置

1
2
roll_df = before_washing.set_index('date')
roll_df = roll_df.rolling(window=6).mean()

set_index('date') 是必须的——不然 rolling 会试图对 date 列求平均(报错)。

注释写明了:# Convert Date Column to Index first so does not get dropped。

window=6:6 个月滚动平均——因为数据是月度的,6 个月能平滑季节性。

⚠️ rolling 默认 min_periods=window——前 5 个月是 NaN(不足 6 个点)。

(12)高亮「手卫生开始」这个时点

1
2
3
4
5
ax.axvline(x=handwashing_start, 
color='crimson',
linestyle='--',
linewidth=2,
label='Handwashing Start')

axvline(x=日期):画一条竖线——标记「干预开始的时点」。

这是「前后对比图」的标准做法:竖线左右就是「before / after」。

linestyle='--':虚线(不与数据线混淆)。

(13)用 ax.fill_between 或 axvspan 涂色

notebook 里用了 ax.axvspan(...) 或 axvspan 类方法把「洗手前」区间涂成浅红——视觉上强化「这是干预前」。

(14)平均数差

1
2
3
avg_prob_before = before_washing.pct_deaths.mean() * 100
avg_prob_after = after_washing.pct_deaths.mean() * 100
mean_diff = avg_prob_before - avg_prob_after

⚠️ 这里用的是 mean()(各月比例的平均),不是「汇总除法」——和前面 bw_rate 的算法不同,结果会略有差异。

两种算法都给,是为了说明「差异不大,结论稳健」——这是好的分析习惯。

(15)np.where:一行做「条件赋值」

1
df_monthly['washing_hands'] = np.where(df_monthly.date < handwashing_start, 'No', 'Yes')

np.where(条件, 真值, 假值):向量化的「三元表达式」。

等价于:

1
df_monthly['washing_hands'] = ['No' if d < handwashing_start else 'Yes' for d in df_monthly.date]

但 np.where 快得多(C 循环)。

这是 Pandas 里「按条件建新列」的首选方法(比 apply 快,比循环快更多)。

(16)箱线图对比

1
2
3
4
5
box = px.box(df_monthly, 
x='washing_hands',
y='pct_deaths',
color='washing_hands',
title='How Have the Stats Changed with Handwashing?')

「Yes / No」两组,各一个箱——中位数、四分位、离群点一目了然。

(17)直方图叠加:barmode='overlay'

1
2
3
4
5
6
7
8
hist = px.histogram(df_monthly, 
x='pct_deaths',
color='washing_hands',
nbins=30,
opacity=0.6,
barmode='overlay',
histnorm='percent',
marginal='box')

五个参数全有用:

参数 作用
nbins=3030 个区间
opacity=0.6半透明(两组重叠处能看见)
barmode='overlay'叠加而非堆叠(两组同区间并排盖住)
histnorm='percent'纵轴是百分比(两组样本量不同,绝对值不可比)
marginal='box'顶部加一条箱线图

histnorm='percent' 是关键:洗手前 98 个月、洗手后 22 个月——数量差 4 倍,用「计数」会比错。

(18)KDE:clip 修正「负死亡率」

1
2
3
4
plt.figure(dpi=200)
# By default the distribution estimate includes a negative death rate!
sns.kdeplot(before_washing.pct_deaths, shade=True)
sns.kdeplot(after_washing.pct_deaths, shade=True)

注释直接点出了问题:KDE 是「核密度估计」,它会向两侧无限延伸——所以在 0 以下也画出了「负死亡率」(物理上不可能)。

修正:

1
2
3
sns.kdeplot(before_washing.pct_deaths, 
shade=True,
clip=(0,1))

clip=(0,1):把估计范围裁剪到 [0,1]——消除「负死亡率」的荒谬。

这是「统计工具要有物理常识约束」的绝佳例子。

**(19)t 检验:判断差异是否「巧合」

1
2
3
4
t_stat, p_value = stats.ttest_ind(a=before_washing.pct_deaths, 
b=after_washing.pct_deaths)
print(f'p-palue is {p_value:.10f}')
print(f't-statstic is {t_stat:.4}')

stats.ttest_ind(a=, b=):独立样本 t 检验——检验「两组均值是否显著不同」。

两个返回值:

值 含义
t_statt 统计量(差异 / 标准误)
p_value「如果两组其实相同,观察到这么大差异的概率」

判读标准:

  • p < 0.01:99% 确信差异不是巧合(markdown 里给的标准);
  • p < 0.05:95% 确信(通用标准)。

这一天算出的 p 约 2e-11——远小于 0.01,所以「洗手确实有效」在统计上成立。

⚠️ 两个拼写错误:p-palue(应 p-value)、t-statstic(应 t-statistic)。

⚠️ t 检验的前提:两组近似正态、方差齐——死亡率分布是右偏的,严格说不满足;但样本量够大(98 vs 22),t 检验比较稳健。

现代做法会用「Mann-Whitney U 检验」(非参数)——结论一样。

(20)结论

markdown 最后一张图是个 GIF,配文:

"What do you conclude from your analysis, Doctor? 😊"

结论:洗手把产妇死亡率从 10.5% 降到 2.7%——Semmelweis 是对的。

历史结局(残忍):他生前被医学界嘲笑,1865 年死于精神病院(被守卫殴打后感染)。二十年后巴斯德的「细菌学说」才证明他对。

这一天不只是「学 pandas」——它是「数据如何推翻权威」的完整案例。

这份代码的问题

  1. 两个 NaN 检查的标签和变量交叉(yearly 查 monthly)。
  2. pct_deaths 用小数、avg_rate 用百分比,单位混用。
  3. markdown 写「1947」(应 1847)。
  4. p-palue / t-statstic 拼写错误。
  5. KDE 默认产生负死亡率(需 clip=(0,1))。
  6. t 检验的「正态性」前提没讨论。
  7. rolling(window=6) 前 5 个是 NaN(图上开头有缺口)。
  8. annual_deaths_by_clinic.csv 只有 12 行(6 年 × 2 诊所),样本极小。

README.md(8 行)

标题 Day 79 - The Tragic Discovery of Handwashing: t-Tests & Distributions,知识点:Data Visualisation、Matplotlib、Plotly、Seaborn、t-Tests。

五个:三个绘图库 + t 检验 + 分布。

这一天的三层结构:

  1. 描述(画图看趋势);
  2. 对比(分组算率);
  3. 推断(t 检验判显著性)。

这三层是「数据分析」的完整链条——从「看到」到「证明」。

微信收款码 微信
支付宝收款码 支付宝
评论