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

Python 100 天 · 第 99 天:美国警察执法致死数据:五表关联分析

这是「Python 100 天」系列第 99 天的学习笔记:美国警察执法致死数据:五表关联分析。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

五份美国人口普查/执法数据:家庭收入中位数、贫困率、高中毕业率、各族裔占比、警察执法致死记录。要回答:哪个州最穷?贫困与学历是否相关?死者中各族裔/性别/年龄如何分布?

README 知识点:去 NaN 与重复、饼图与环形图、分组柱状图与箱线图、时间戳清洗。

数据主题敏感:分析时只描述数字,不做因果归因,不针对任何群体下结论。这是数据分析的基本伦理。

一、五份数据、五种编码问题

1
2
3
4
5
df_hh_income = pd.read_csv('Median_Household_Income_2015.csv', encoding="windows-1252")
df_pct_poverty = pd.read_csv('Pct_People_Below_Poverty_Level.csv', encoding="windows-1252")
df_pct_completed_hs = pd.read_csv('Pct_Over_25_Completed_High_School.csv', encoding="windows-1252")
df_share_race_city = pd.read_csv('Share_of_Race_By_City.csv', encoding="windows-1252")
df_fatalities = pd.read_csv('Deaths_by_Police_US.csv', encoding="windows-1252")

encoding="windows-1252":这批数据是 Excel 导出的,含 é、ñ 之类字符,用默认 UTF-8 会 UnicodeDecodeError。遇到编码错误先试 windows-1252(西欧)和 latin-1(万能兜底)。

二、"数字列"其实是字符串

1
2
df_pct_poverty.poverty_rate.replace('-', np.nan, regex=True, inplace=True)
df_pct_poverty.poverty_rate = df_pct_poverty.poverty_rate.astype(float)

普查数据用 "-" 表示"缺失",不是数字 0。直接 astype(float) 会 ValueError: could not convert string to float: '-'。

先替换成 np.nan 再转类型,这是清洗"用符号表示缺失"的固定套路。regex=True 是因为 replace 默认按字面匹配,这里其实可以不加(- 不是正则元字符)。

三、按州聚合

1
2
poverty = df_pct_poverty.groupby('Geographic Area')['poverty_rate'].mean().sort_values(ascending=False)
graduation = df_pct_completed_hs.groupby('Geographic Area')['percent_completed_hs'].mean()

数据是"县级"的,要回答"州级"问题就必须 groupby('Geographic Area') 求均值。这就是"降粒度聚合"(和 Day 77 的年份→年代一样)。

注意:mean() 会跳过 NaN,所以"有 5 个县有数据、95 个县缺失"的州,均值只代表那 5 个县——样本量没被考虑进去。严谨做法是同时算 count()。

四、两列对比:双 y 轴不要乱用

1
2
3
4
ax1 = plt.gca()
ax2 = ax1.twinx()
ax1.plot(poverty_vs.index, poverty_vs, color='#E6232E', linestyle='--', linewidth=3)
ax2.plot(graduation_vs.index, graduation_vs, color='skyblue', marker='o', linewidth=3)

贫困率和毕业率的量级接近(都是 0–40),其实不需要双轴,一条 y 轴就能比。双轴在这里反而让读者误以为两者量级不同。

双轴的正当理由只有一个:两个量的单位/量级差一个数量级以上(比如股价 vs 搜索指数,Day 74)。

五、堆叠柱状图:各族裔占比

1
2
3
4
5
6
7
for n in range(len(racial)):
plt.bar(racial.index[n], racial['share_white'][n], color=color_list[0])
plt.bar(racial.index[n], racial['share_black'][n], color=color_list[1])
...

white_legend = mpatches.Patch(label='White', color=color_list[0])
plt.legend(handles=[white_legend, ...])

对每个州依次画 5 根柱子(不传 bottom 参数,所以它们会重叠,不是堆叠)。

要真正堆叠必须累积 bottom:

1
2
3
4
5
bottom = np.zeros(len(racial))
for col in columns:
plt.bar(racial.index, racial[col], bottom=bottom, label=col)
bottom += racial[col].values
plt.legend()

mpatches.Patch 是"手工造图例"的办法(当图形不是标准 bar/plot 时用)。

六、环形图:中间挖空

1
2
3
plt.pie(killed, labels=killed.index, autopct=make_autopct(killed), shadow=True, startangle=60, pctdistance=1.4, labeldistance=1.1)
my_circle = plt.Circle((0,0), 0.7, color='white')
plt.gcf().gca().add_artist(my_circle)

Matplotlib 没有内置环形图,做法是"画饼图 + 在中间盖一个白色圆"。pctdistance=1.4 把百分比推到圆外,labeldistance=1.1 控制标签距离。

make_autopct 是个闭包:它接收整个 values 序列,返回一个"能把百分比换算成绝对数"的函数,于是标签能显示 "12.34% (56)"。

代码全文(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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# %pip 是 Jupyter/Colab 的魔术命令(不是 Python 语法),用来装依赖。
# 以 ! 开头的是 shell 命令:wget 下 orca(plotly 导出静态图的可执行文件),
# chmod +x 给它执行权限,apt-get install xvfb 装虚拟显示(无头环境画图要用)。
%pip install --upgrade plotly
!wget https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage -O /usr/local/bin/orca
!chmod +x /usr/local/bin/orca
!apt-get install xvfb libgtk2.0-0 libgconf-2-4

# numpy:数值计算;pandas:表格;plotly.express / graph_objects:交互图与地图;
# matplotlib.pyplot:静态图;seaborn:统计图;Counter:计数;
# mpatches / colors:自定义图例色块、取颜色表;random:随机抽样。
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import seaborn as sns

from collections import Counter

import matplotlib.patches as mpatches
import matplotlib.colors as colors

import random

# 全局显示格式:浮点数显示两位小数并带千分位逗号(只影响显示,不改数据)。
pd.options.display.float_format = '{:,.2f}'.format

# encoding='windows-1252':这几份 CSV 是西文 Windows 编码,用 utf-8 读会报错。
# pd.read_csv 返回 DataFrame,列名取 CSV 第一行。
df_hh_income = pd.read_csv('Median_Household_Income_2015.csv', encoding="windows-1252")
df_pct_poverty = pd.read_csv('Pct_People_Below_Poverty_Level.csv', encoding="windows-1252")
df_pct_completed_hs = pd.read_csv('Pct_Over_25_Completed_High_School.csv', encoding="windows-1252")
df_share_race_city = pd.read_csv('Share_of_Race_By_City.csv', encoding="windows-1252")
df_fatalities = pd.read_csv('Deaths_by_Police_US.csv', encoding="windows-1252")

# info():每列的类型和非空数量,用来判断该列是否数值、有没有缺失。
# 逗号表达式只是把三个调用写在一行,三个都会执行并打印。
df_hh_income.info(), df_pct_poverty.info(), df_pct_completed_hs.info()

# 直接写变量名,notebook 会把 DataFrame 渲染成表格(只显示前几行和后几行)。
df_share_race_city

# 同上,看警方枪击致死表的列结构与样例。
df_fatalities

# isnull():逐格判断是否缺失;.any() 把每列压成一个布尔值,True 表示该列有空值。
df_hh_income.isnull().any()

# 把收入列的 NaN 填成 0 —— 会让均值偏低,属于“能跑但不严谨”的处理,
# 更合理的是填中位数或直接 dropna()。
df_hh_income['Median Income'] = df_hh_income['Median Income'].replace(np.nan, 0)

# 复查填充结果:现在应该全是 False。
df_hh_income.isnull().any()

# 贫困率表缺失检查。
df_pct_poverty.isnull().any()

# 高中毕业率表缺失检查。
df_pct_completed_hs.isnull().any()

# 种族占比表缺失检查。
df_share_race_city.isnull().any()

# 枪击表缺失检查(age / race / flee 等列都有空缺)。
df_fatalities.isnull().any()

# 写法冗余:isnull().any() 已经把整列压成一个布尔值,再 .sum() 只是把 True 变成 1。
df_fatalities.armed.isnull().any().sum()

# 同上,race 列是否有缺失。
df_fatalities.race.isnull().any().sum()

# 同上,flee(是否逃跑)列是否有缺失。
df_fatalities.flee.isnull().any().sum()

# duplicated():判断每行是否与前面某行完全重复;.values.any() 看是否存在任一重复行。
# CHECK DUPLICATE ROWS
df_hh_income.duplicated().values.any()

# 贫困率表是否有完全重复的行。
df_pct_poverty.duplicated().values.any()

# 毕业率表重复行检查。
df_pct_completed_hs.duplicated().values.any()

# 种族占比表重复行检查。
df_share_race_city.duplicated().values.any()

# 枪击表重复行检查。
df_fatalities.duplicated().values.any()

# 再看一次贫困率表的类型:poverty_rate 是 object(字符串),因为里面混了 '-',
# 必须先清洗才能求均值。
df_pct_poverty.info()

# unique():这一列所有不重复的取值 —— 确认州名写法(全大写英文)。
df_pct_poverty['Geographic Area'].unique()

# 把 '-' 替换成 NaN:regex=True 让第一个参数按正则处理,inplace 就地修改。
# 然后用 astype(float) 把整列转成浮点数,才能参与计算。
df_pct_poverty.poverty_rate.unique()
df_pct_poverty.poverty_rate.replace('-', np.nan, regex=True, inplace=True)
df_pct_poverty.poverty_rate = df_pct_poverty.poverty_rate.astype(float)

# groupby('Geographic Area'):按州分组;['poverty_rate'].mean():组内均值;
# sort_values(ascending=False):从高到低排。结果是 Series,索引是州名。
poverty = df_pct_poverty.groupby('Geographic Area')['poverty_rate'].mean().sort_values(ascending=False)
poverty

# plt.style.use('seaborn-deep') 是旧版 matplotlib 的样式名,新版已移除,
# 会报警告,应改成 'seaborn-v0_8-deep'。
# figsize=(14,4):画布 14×4 英寸;suptitle 是整张图的标题,xlabel/ylabel 是坐标轴名。
# 循环里逐个州画一根竖柱;xticks(rotation=90) 让州名竖排避免重叠。
plt.style.use('seaborn-deep')

plt.figure(figsize=(14,4))
plt.suptitle('Poverty Rate in each US State')
plt.ylabel('Poverty Rate', fontsize=14)
plt.xlabel('US State', fontsize=14)

for n in range(len(poverty)):
plt.xticks(fontsize=10, rotation=90)
plt.yticks(fontsize=14)
plt.bar(poverty.index[n], poverty[n])

plt.show()

# head():前 5 行,确认列名是 Geographic Area / percent_completed_hs。
df_pct_completed_hs.head()

# 同样的清洗:'-' → NaN,再转 float。
df_pct_completed_hs.percent_completed_hs.replace('-', np.nan, regex=True, inplace=True)
df_pct_completed_hs.percent_completed_hs = df_pct_completed_hs.percent_completed_hs.astype(float)

# 按州求毕业率均值,降序排。
graduation = df_pct_completed_hs.groupby('Geographic Area')['percent_completed_hs'].mean().sort_values(ascending=False)
graduation

# 这里用 scatter 画“州 vs 毕业率”:每个州只有一个点,看起来像柱状图但其实是散点,
# 想表达排名用 bar 更直观。
plt.figure(figsize=(14,4))
plt.suptitle('High School Graduation Rate by US State')
plt.ylabel('High School Graduation Rate', fontsize=14)
plt.xlabel('US State', fontsize=14)

plt.xticks(fontsize=10, rotation=90)
plt.yticks(fontsize=14)
plt.scatter(graduation.index, graduation)

plt.show()

# 只做 groupby+mean 不做排序:得到按州名排序的毕业率 Series,供双轴图对齐用。
graduation_vs = df_pct_completed_hs.groupby('Geographic Area')['percent_completed_hs'].mean()
graduation_vs

# 同样的写法得到贫困率 Series,两个 Series 的索引顺序一致,才能叠在同一张图上。
poverty_vs = df_pct_poverty.groupby('Geographic Area')['poverty_rate'].mean()
poverty_vs

# twinx():共享 x 轴、另开一条 y 轴(ax2),两套量纲才能画在一张图里。
# gca():拿到当前的坐标轴对象。set_ylabel 的 color 参数同时改轴标签和刻度颜色。
# plot 里 color 可以用 HEX,也可以直接用颜色名(skyblue);linestyle='--' 虚线,marker='o' 圆点。
plt.figure(figsize=(14,3))
plt.suptitle('Poverty Rates and High School Graduation Rates', fontsize=14)
plt.xlabel('US State', fontsize=12)
plt.xticks(fontsize=10, rotation=55)

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

ax1.set_ylabel('Poverty', color='#E6232E') # can use a HEX code
ax2.set_ylabel('Graduation', color='skyblue') # or a named colour

ax1.plot(poverty_vs.index, poverty_vs, color='#E6232E', linewidth=3, linestyle='--')
ax2.plot(graduation_vs.index, graduation_vs, color='skyblue', linewidth=3, marker='o')

plt.show()

# to_numeric:把可能残留的字符串列强制转数值。
# groupby(as_index=False) 让州名变成普通列而不是索引;
# agg({'poverty_rate': pd.Series.mean}) 指定用均值聚合(等价于 .mean())。
df_pct_poverty.poverty_rate = pd.to_numeric(df_pct_poverty.poverty_rate)
df_pct_poverty.sort_values('poverty_rate', ascending=False, inplace=True)
poverty = df_pct_poverty.groupby('Geographic Area', as_index=False).agg({'poverty_rate': pd.Series.mean})

# 毕业率同样处理,得到 hs 表。
df_pct_completed_hs.percent_completed_hs = pd.to_numeric(df_pct_completed_hs.percent_completed_hs)
df_pct_completed_hs.sort_values('percent_completed_hs', ascending=False, inplace=True)
hs = df_pct_completed_hs.groupby('Geographic Area', as_index=False).agg({'percent_completed_hs': pd.Series.mean})

# merge:按州名做内连接(只保留两边都有的州),得到一张宽表供画图。
merged = pd.merge(hs, poverty, on=['Geographic Area'], how='inner')

# jointplot(kind='kde'):两个变量的联合分布,中间是核密度等高线,两侧是各自的一维分布。
sns.set_theme(style="ticks")

sns.jointplot(x='poverty_rate', y='percent_completed_hs', data=merged, kind='kde')
plt.show()

# lmplot:散点 + 线性回归直线 + 95% 置信带。
# set_theme(color_codes=True) 是旧 API,新版 seaborn 已废弃,直接用默认调色即可。
sns.set_theme(color_codes=True)

sns.lmplot(x='poverty_rate', y='percent_completed_hs', data=merged)
plt.show()

# regplot:只画回归线与置信带(没有分面能力),和 lmplot 输出接近。
sns.regplot(x='poverty_rate', y='percent_completed_hs', data=merged)
plt.show()

# 看种族占比表的原始样子:每个城市一行,五个 share 列是字符串百分比。
df_share_race_city

# 对五列统一 apply(pd.to_numeric):能转的转成数字,转不了的(如空串)变 NaN(errors='coerce')。
df_share_race_city[['share_white', 'share_black', 'share_native_american', 'share_asian', 'share_hispanic']] = df_share_race_city[['share_white', 'share_black', 'share_native_american', 'share_asian', 'share_hispanic']].apply(pd.to_numeric, errors='coerce')

# 按州分组,对五个种族列各求均值 —— 得到“这个州平均种族构成”。
racial = df_share_race_city.groupby('Geographic area').agg({'share_white': 'mean', 'share_black': 'mean', 'share_native_american': 'mean', 'share_asian': 'mean', 'share_hispanic': 'mean'})
racial.head()

# np.arange(len(racial)):生成 0,1,2… 的位置数组,用于把 x 刻度对齐到州名。
# colors._colors_full_map 是 matplotlib 的内部颜色字典(私有属性,版本升级可能改动)。
# 注意:连续 5 次 plt.bar 没传 bottom,五个柱子会互相覆盖而不是堆叠,
# 真正的堆叠要写成 plt.bar(x, y1); plt.bar(x, y2, bottom=y1) 逐层累加。
# mpatches.Patch 造一个只有颜色和图例文字的“假图块”,再交给 plt.legend(handles=...) 显示。
x_indexes = np.arange(len(racial))

color_list = list(colors._colors_full_map.values())

plt.figure(figsize=(14,8))
plt.suptitle('Racial Makeup of Each US State')
plt.ylabel('%', fontsize=14)
plt.xlabel('US State', fontsize=14)

labels = []
for n in range(len(racial)):
plt.bar(racial.index[n], racial['share_white'][n], color=color_list[0])
plt.bar(racial.index[n], racial['share_black'][n], color=color_list[1])
plt.bar(racial.index[n], racial['share_native_american'][n], color=color_list[2])
plt.bar(racial.index[n], racial['share_asian'][n], color=color_list[10])
plt.bar(racial.index[n], racial['share_hispanic'][n], color=color_list[9])
labels.append(racial.index[n])

white_legend = mpatches.Patch(label='White', color=color_list[0])
black_legend = mpatches.Patch(label='Black', color=color_list[1])
native_american_legend = mpatches.Patch(label='Native American', color=color_list[2])
asian_legend = mpatches.Patch(label='Asian', color=color_list[10])
hispanic_legend = mpatches.Patch(label='Hispanic', color=color_list[9])

plt.legend(handles=[white_legend, black_legend, native_american_legend, asian_legend, hispanic_legend], loc='best', frameon=False)

plt.xticks(ticks=x_indexes, labels=labels, fontsize=10, rotation=75)
plt.yticks(fontsize=10)

plt.show()

# value_counts():每个种族各有多少人被打死(降序)。
# unique():数据里出现过哪些种族标签,检查有没有拼写变体。
killed = df_fatalities.race.value_counts()
killed
df_fatalities.race.unique()

# 闭包:make_autopct 返回一个函数给 pie 的 autopct 用。
# matplotlib 会把百分比 pct 传进来,这里用总人数反算出具体人数,显示成 “12.34% (56)”。
# pie 参数:autopct 百分比标注格式、shadow 阴影、startangle 起始角度、
# pctdistance / labeldistance 控制百分比文字与标签离圆心的距离。
# plt.Circle((0,0), 0.7, color='white') 在中心盖一个白圆 → 饼图变甜甜圈;
# gcf() 取当前 figure,gca().add_artist() 把圆加进坐标系。
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return '{p:.2f}% ({v:d})'.format(p=pct,v=val)
return my_autopct

plt.figure(figsize=(10,10))
plt.suptitle('People Killed by Race')
plt.pie(killed, labels=killed.index, autopct=make_autopct(killed), shadow=True, startangle=60, pctdistance=1.4, labeldistance=1.1)

my_circle=plt.Circle( (0,0), 0.7, color='white')
p=plt.gcf()
p.gca().add_artist(my_circle)

plt.show()

# 按性别统计死亡人数。
killed_gender = df_fatalities.gender.value_counts()
killed_gender

# 同一套 pie 参数画性别占比。
plt.figure(figsize=(10,10))
plt.suptitle('Total Number of Deaths of Men and Women')
plt.pie(killed_gender, labels=killed_gender.index, autopct=make_autopct(killed_gender), shadow=True, startangle=60, pctdistance=1.4, labeldistance=1.1)

plt.show()

# 年龄缺失填 0:会把“未知年龄”混进 0 岁,箱线图的下须会被拉低(更合理是 dropna)。
# 只取三列做一个子表,后面画箱线图用。
df_fatalities['age'] = df_fatalities['age'].replace(np.nan, 0)
df_fatalities.age.isnull().any()
death_age = df_fatalities[['age', 'manner_of_death', 'gender']]
death_age

# boxplot:x=数值列 age、y=类别列 manner_of_death、hue=gender 分组上色。
# 通常习惯是 x=类别、y=数值,这里参数方向反了,图会变成横向箱线。
plt.figure(figsize=(10,10))
sns.boxplot(x='age', y='manner_of_death', hue='gender', data=death_age)
plt.show()

# 看 armed 列有哪些取值(枪、刀、玩具枪……五花八门)。
df_fatalities.armed.unique()

# 先 copy 一份,避免改动原始 df。
# weapons 是人工整理出来的“各种武器写法”清单。
# replace(weapons, 'armed'):清单里出现的值统一替换成 'armed',把几十种写法归成两类。
# 注意这种精确匹配很脆弱:清单漏一个写法,那一条就不会被归类。
armed = df_fatalities.copy()

weapons = ['gun', 'toy weapon', 'nail gun', 'knife', 'vehicle',
'shovel', 'hammer', 'hatchet', 'undetermined', 'sword', 'machete',
'box cutter', 'metal object', 'screwdriver', 'lawn mower blade',
'flagpole', 'guns and explosives', 'cordless drill', 'crossbow',
'metal pole', 'Taser', 'metal pipe', 'metal hand tool',
'blunt object', 'metal stick', 'sharp object', 'meat cleaver',
'carjack', 'chain', "contractor's level", 'unknown weapon',
'stapler', 'beer bottle', 'bean-bag gun',
'baseball bat and fireplace poker', 'straight edge razor',
'gun and knife', 'ax', 'brick', 'baseball bat', 'hand torch',
'chain saw', 'garden tool', 'scissors', 'pole', 'pick-axe',
'flashlight', 'baton', 'spear', 'pitchfork', 'hatchet and gun',
'rock', 'piece of wood', 'bayonet', 'pipe', 'glass shard',
'motorcycle', 'metal rake', 'crowbar', 'oar', 'machete and gun',
'tire iron', 'air conditioner', 'pole and knife',
'baseball bat and bottle', 'fireworks', 'pen']

armed.armed = armed.armed.replace(weapons, 'armed')

armed.armed.unique()

# 归类后 armed / unarmed / undetermined 各多少人。
percentage = armed.armed.value_counts()
percentage

# 画饼图看“被枪杀者是否持械”的比例。
plt.figure(figsize=(10,10))
plt.suptitle('Police Killings')
plt.pie(percentage, labels=percentage.index, autopct=make_autopct(percentage), shadow=True, startangle=60, pctdistance=1.4, labeldistance=1.1)

plt.show()

# 未归类的原始武器计数,用于下一张横向条形图。
arm = df_fatalities.armed.value_counts()
arm

# barh:横向条形图,类别多了以后比竖柱更好读。
# figsize 高度给到 16,是因为武器种类有 60 多种。
plt.figure(figsize=(10,16))
plt.suptitle('What kind of weapon the deceased was carrying')
plt.ylabel('Weapon', fontsize=14)
plt.xlabel('Total', fontsize=14)

for n in range(len(arm)):
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.barh(arm.index[n], arm[n])

plt.show()

# loc[布尔条件]:按条件筛行,返回子表。
# id.count():这一列非空值的个数(等于行数)。
# 注意算法问题:分母用的是“25 岁以上人数”,所以结果不是“占全体的比例”,
# 正确写法应是 under / (under + over)。
junior = df_fatalities.loc[df_fatalities['age'] < 25]
under = junior.id.count()

senior = df_fatalities.loc[df_fatalities['age'] > 25]
over = senior.id.count()

print(f"{round((under / over) * 100)}% of people killed were under 25 years old.")

# 再打印整张表,检查 age 列的分布。
df_fatalities

# histplot + kde=True:直方图叠加核密度曲线,看年龄分布形状。
plt.figure(figsize=(14,8))
plt.suptitle('Ages of The People Killed by Police')
sns.histplot(data=df_fatalities, x="age", kde=True)
plt.show()

# hue='race' 按种族分组、element='step' 用阶梯线避免柱子互相遮挡。
plt.figure(figsize=(14,8))
plt.suptitle('Ages of The People Killed by Police by Race')
sns.histplot(data=df_fatalities, x="age", kde=True, hue='race', element='step')
plt.show()

# 各种族死亡总数。
race_kill = df_fatalities.race.value_counts()
race_kill

# 饼图(复用上面定义的 make_autopct)。
plt.figure(figsize=(10,10))
plt.suptitle('Race of The Killed People')
plt.pie(race_kill, labels=race_kill.index, autopct=make_autopct(race_kill), shadow=True, startangle=60, pctdistance=1.4, labeldistance=1.1)
plt.show()

# 是否有精神疾病迹象的计数。
df_fatalities
mental = df_fatalities.signs_of_mental_illness.value_counts()
mental

# 饼图看比例。
plt.figure(figsize=(10,10))
plt.suptitle('Killed by Police that have a mental illness')
plt.pie(mental, labels=mental.index, autopct=make_autopct(mental), shadow=True, startangle=60, pctdistance=1.4, labeldistance=1.1)
plt.show()

# 按城市计数,取前 10 名。
cities = df_fatalities.city.value_counts().head(10)
cities

# bar(x, height):竖柱;label=cities.index 只影响图例,这里没调 legend 所以看不到。
# linewidth=3 让柱子描边更粗一点。
plt.figure(figsize=(14,8))
plt.suptitle('The Top 10 Cities With The Most Police Killings', fontsize=16)
plt.ylabel('Police Killings', fontsize=14)
plt.xlabel('City', fontsize=14)
plt.xticks(fontsize=12, rotation=45)
plt.yticks(fontsize=12)
plt.bar(cities.index, cities, label=cities.index, linewidth=3)
plt.show()

# 逐个城市画种族构成小图:每次 plt.show() 都会单独出一张图(共 10 张)。
# 这种循环里反复 show 的写法在 notebook 里很啰嗦,用分面(FacetGrid)更合适。
top = df_fatalities[['city', 'race']]
for c in cities.index:
top_cities = top.loc[top['city'] == c]
city = top_cities.race.value_counts()
plt.bar(city.index, city, label=c)
plt.legend(loc='best')
plt.show()

# groupby('state').size():每个州的行数,也就是死亡人数;降序排便于看最危险的州。
states_to_map = df_fatalities.groupby('state').size().sort_values(ascending=False)
states_to_map

# go.Choropleth:plotly 的地图对象。locationmode='USA-states' 表示按美国州代码上色
# (数据里 state 已是两位缩写,正好匹配);z 是上色数值,colorscale 是色阶。
# update_layout(geo_scope='usa') 把地图视野锁在美国;
# fig.show('png') 输出静态图,需要额外安装 kaleido,否则会报错。
fig = go.Figure(data=go.Choropleth(
locations=states_to_map.index,
z = states_to_map,
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "Police Killings",
))

fig.update_layout(
title_text = 'Police Killings by US State',
geo_scope='usa',
)

fig.show("png")

# to_datetime 把字符串日期转成时间类型(infer_datetime_format 在新版 pandas 已废弃);
# .dt.to_period('m') 归到“月”这一粒度,再 astype(str) 变成 '2015-01' 这样的标签,方便分组。
monthly_fatalities = df_fatalities.copy()
monthly_fatalities.date = pd.to_datetime(monthly_fatalities.date, infer_datetime_format=True).dt.to_period('m')
monthly_fatalities.date = monthly_fatalities.date.astype(str)

# 按月份分组计数,得到每月死亡人数的时间序列。
history = monthly_fatalities.groupby('date').size()
history

# 折线图看趋势;xticks 传入字符串索引并旋转 65 度,否则月份标签会挤在一起。
plt.figure(figsize=(14,6))
plt.plot(history.index, history, linewidth=3)
plt.xticks(ticks=history.index, fontsize=10, rotation=65)
plt.suptitle('Police Killings Over Time')
plt.xlabel('Month', fontsize=14)
plt.ylabel('Killings', fontsize=14)

plt.show()

走读与要点

  1. 开头三行 !wget orca / !chmod / !apt-get:Colab 专用(装 Plotly 的静态导出工具)。本地跑要删掉。
  2. 五份 CSV 用 windows-1252 读入。
  3. 逐个 isnull().any() 体检;df_hh_income['Median Income'].replace(np.nan, 0) 把缺失填 0(这一步有风险,见下)。
  4. 贫困率/毕业率的 "-" → NaN → float。
  5. 按州聚合 → 柱状图/散点图。
  6. 两率对比(双轴)。
  7. pd.merge(hs, poverty, on='Geographic Area') 合并成一张表。
  8. sns.jointplot(kind='kde') 看二维密度;sns.lmplot / sns.regplot 看线性趋势。
  9. 族裔占比的柱状图 + 手工图例。
  10. 死者按种族/性别的环形图;年龄字段清洗。

这份代码的问题

(1) 把缺失收入填 0

1
df_hh_income['Median Income'] = df_hh_income['Median Income'].replace(np.nan, 0)

0 是一个真实的可能值(虽然收入中位数不会是 0),填 0 会让该州的平均收入被严重拉低。正确做法是保留 NaN 让 mean() 自动跳过,或填"该州的中位数"。

"用 0 填缺失"是数据分析里最常见的错误之一,因为它悄悄改变了分布。

(2) np.na 不存在

1
df_fatalities['age'] = df_fatalities['age'].replace(np.na...

应该是 np.nan。np.na 会 AttributeError。这是笔误,但说明这段代码没跑通就提交了。

(3) 双轴用得没必要

见上。贫困率和毕业率应该画在同一根轴上,或者画散点图(后面确实画了 lmplot,那才是正确的做法)。

(4) 堆叠柱状图实际上是重叠的

没传 bottom,五根柱子从同一条基线出发,后画的会盖住先画的。图上只能看到最后一根。

(5) color_list[1] 这种取色方式

colors._colors_full_map.values() 是内部字典的随机顺序(Python 3.7+ 按插入顺序,但仍然不可控)。今天跑是蓝、明天跑可能是红。应该用明确的十六进制色值。

(6) groupby 用 'Geographic Area' 但族裔表用 'Geographic area'

一个首字母大写,一个小写——如果两份表要 merge,这个差异会让 KeyError。

(7) 伦理与解读

"某族裔死者比例高"不能直接推出"警察针对某族裔":还要看该族裔在总人口中的占比、各地犯罪率、执法接触次数。缺少分母的比例是没有意义的。这段分析只做了分子,任何结论都必须加限定。

运行结果

  • 贫困率柱状图:南部/阿巴拉契亚地区偏高;
  • 毕业率散点图:北部/中西部偏高;
  • 贫困 vs 毕业的 lmplot:明显负相关(越穷的地方毕业率越低);
  • 族裔占比柱状图(实际是重叠的);
  • 死者种族/性别环形图:男性占绝对多数;
  • 年龄分布:集中在 20–40 岁。

易错点

  1. 编码错误:先试 windows-1252。
  2. "-" 当数字:先 replace 成 NaN。
  3. 用 0 填缺失:改变分布,均值失真。
  4. plt.pie 的 labels 和 values 长度不等:报错。
  5. merge 的键名大小写不一致:KeyError。

动手改

  • 删掉三行 Colab 专用命令。
  • 修 np.na 笔误。
  • 收入缺失保留 NaN,不填 0。
  • 用 bottom 参数实现真正的堆叠柱状图。
  • 给族裔比例加上"占总人口比例"作为分母,再谈差异。

源文件逐个讲解

7 个文件:

文件 规模 职责
day99.ipynb101 个 cell美国警察枪击致死数据分析
Deaths_by_Police_US.csv2535 行 × 14 列(224KB)《华盛顿邮报》警察枪击致死数据库
Median_Household_Income_2015.csv29322 行 × 3 列(696KB)2015 年各城市家庭收入中位数
Pct_People_Below_Poverty_Level.csv29329 行 × 3 列(652KB)各城市贫困率
Pct_Over_25_Completed_High_School.csv29329 行 × 3 列(664KB)25 岁以上高中完成率
Share_of_Race_By_City.csv29268 行 × 7 列(1.0MB)各城市种族构成
README.md10 行说明页

五张表的「粒度」不一样,这是全篇最关键的一点:

表 一行代表什么 行数
Deaths_by_Police_US「一个人」2535
四张普查表「一个城市(CDP/place)」约 29300

「29300 个城市」对「2535 个死者」——任何「按州汇总再对比」的操作,都必须先想清楚「分母是什么」。

⚠️ 四张普查表全是「按城市」的,不是「按州」的——这是本 notebook 大量统计错误的根源(详下)。

Deaths_by_Police_US.csv(2535 × 14)

14 列:

列 取值示例 含义
id3编号(不连续,说明原库更大)
nameTim Elliot姓名
date02/01/15⚠️ 美式 月/日/年,两位年份
manner_of_deathshot / shot and Tasered死法
armedgun / unarmed / toy weapon / nail gun…⚠️ 60+ 种自由文本
age53⚠️ 有缺失
genderM / F⚠️ 只有两个值,也有人缺失
raceW / B / H / A / N / O白人/黑人/西语裔/亚裔/原住民/其他
city / stateShelton / WAstate 是两字母缩写
signs_of_mental_illnessTRUE / FALSE精神疾病迹象
threat_levelattack / other / undetermined威胁等级
fleeNot fleeing / Car / Foot是否逃跑
body_cameraTRUE / FALSE是否佩戴执法记录仪

三个「数据本身的坑」:

  1. date 是 02/01/15——不是 ISO 格式,pd.to_datetime 会「按美式解读」(2 月 1 日,不是 1 月 2 日)。
  2. armed 是「自由文本」——60 多种写法(gun、guns and explosives、machete and gun…)——必须「重分类」才能算比例。
  3. age 有缺失——而 notebook 里「用 0 填充」(见下,这是最严重的一个错误)。

day99.ipynb(101 cell)

(1)cell 3:一个「只在 Colab 能用」的格子

1
2
3
4
%pip install --upgrade plotly
!wget https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage -O /usr/local/bin/orca
!chmod +x /usr/local/bin/orca
!apt-get install xvfb libgtk2.0-0 libgconf-2-4

这是「为了把 Plotly 图导出成 png」而装的 orca(fig.show("png") 需要它)。

⚠️ 三个问题:

  • !wget / !apt-get 是「Colab(Linux)专属」——本地 macOS/Windows 上「一行都跑不了」;
  • orca 项目 2022 年已「停止维护」;
  • 现在正确做法是 pip install kaleido(Plotly 官方替代品)。

(2)cell 5:六个 import,三个没用

1
2
3
4
5
6
7
8
9
10
11
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import seaborn as sns

from collections import Counter
import matplotlib.patches as mpatches
import matplotlib.colors as colors
import random
导入了 用了吗
np / pd / px / plt / sns✅
go✅ 只在 cell 95(choropleth)
mpatches✅ cell 57(图例 patch)
colors✅ cell 57(colors._colors_full_map)
Counter❌ 一次没用
random❌ 一次没用

(3)cell 9:五张表都要 encoding="windows-1252"

1
df_hh_income = pd.read_csv('Median_Household_Income_2015.csv', encoding="windows-1252")

为什么? 这些 CSV 是「从美国普查局网站下载、用 Excel 存过的」——里面含 é、ñ、–(长破折号)等「cp1252 字符」,用默认的 utf-8 读会「UnicodeDecodeError」。

「遇到 UnicodeDecodeError 就试 windows-1252」——这是「读美国老数据」的第一反应。

⚠️ 但 windows-1252 不是「万能钥匙」:中文 GBK 文件用它读会「变成乱码但不报错」——乱码比报错更危险。

(4)cell 16:NaN → 0 的「收入」

1
df_hh_income['Median Income'] = df_hh_income['Median Income'].replace(np.nan, 0)

⚠️「收入中位数 = 0」在现实里「不存在」(一个城市不可能「人人零收入」)。

填 0 的后果:任何「按州求均值」都会「被这些 0 拉低」——而「哪些城市缺收入数据」不是随机的(往往是小地方/难统计的地方)——这会「系统性低估」贫困州的收入。

更合理的三种处理:

做法 适用
dropna()(删行)缺失少(<5%)
填「该州中位数」缺失与地区相关
填 0 但「单独标记」「0」本身有含义(如「无数据=未申报」)

「填 0」在这里是「最省事也最误导」的选择。

(5)cell 22:.isnull().any().sum() 的三层套娃

1
df_fatalities.armed.isnull().any().sum()

拆开看:

步 结果
df_fatalities.armed.isnull()2535 个 True/False
.any()「有没有任何一个 True」→ 一个 bool
.sum()bool 求和 → 0 或 1

所以这个表达式「永远返回 0 或 1」——它回答的是「有没有缺失」,不是「缺几个」。

想数「缺几个」,应该 .isnull().sum()(去掉 .any())。

(6)cell 33:'-' 是「缺失值的另一种写法」

1
2
3
df_pct_poverty.poverty_rate.unique()
df_pct_poverty.poverty_rate.replace('-', np.nan, regex=True, inplace=True)
df_pct_poverty.poverty_rate = df_pct_poverty.poverty_rate.astype(float)

⚠️ 这是「美国普查数据的经典坑」:缺失值不写空,写一个 -(有时是 (X)、N/A、**)。

pd.read_csv 会把整列读成 object——必须先「把 - 换成 NaN」,再 astype(float)。

⚠️ regex=True 在这里是「多余且危险」的:'-' 是普通字符,不需要正则;但如果某列有 '.' 这种「正则元字符」,regex=True 会「把它当通配符」,替换掉一切。

正确写法:pd.read_csv(..., na_values=['-'])——在读的时候就把 - 认成 NaN,一步到位。

(7)cell 34:mean() —— 全篇最大的统计错误

1
poverty = df_pct_poverty.groupby('Geographic Area')['poverty_rate'].mean().sort_values(ascending=False)

Geographic Area 是「州」,但「一行是一个城市」——所以这是「该州所有城市的贫困率的「简单平均」」。

为什么错? 简单平均 = 「每个城市一票」——洛杉矶(400 万人)和「某 CDP(300 人)」权重一样。

正确做法是「按人口加权」:

$$text{州贫困率} = frac{sum (text{城市贫困率} times text{城市人口})}{sum text{城市人口}}$$

⚠️ 而这张表里「没有人口列」——所以你「压根算不出」正确的州贫困率。

「这一格的结果」只能叫「各州「城市平均贫困率」」,不能叫「各州贫困率」——而 notebook 的标题写的是「Poverty Rate in each US State」。

这是「数据分析里最容易被忽略、后果最大的一类错误」:「聚合层级」和「指标定义」不匹配。

(8)cell 35:一根一根画柱子

1
2
3
4
5
plt.style.use('seaborn-deep')
for n in range(len(poverty)):
plt.xticks(fontsize=10, rotation=90)
plt.yticks(fontsize=14)
plt.bar(poverty.index[n], poverty[n])

⚠️ 三个问题:

① plt.style.use('seaborn-deep') 在 matplotlib 3.6+ 已「移除」

报错:OSError: 'seaborn-deep' is not a valid package style。

应改成 plt.style.use('seaborn-v0_8-deep'),或者直接用 sns.set_theme()。

② plt.bar(一个字符串, 一个数) 循环 51 次

plt.bar 本身就能接受「列表」:plt.bar(poverty.index, poverty.values)——一次画完,快 50 倍。

③ plt.xticks(...) 写在循环里

每画一根柱子就设一次刻度——最后一根时会「重设 51 次」——纯浪费。

(9)cell 44:双 Y 轴 ——「看起来相关」的陷阱

1
2
3
4
5
6
ax1 = plt.gca()
ax2 = ax1.twinx()
ax1.set_ylabel('Poverty', color='#E6232E')
ax2.set_ylabel('Graduation', color='skyblue')
ax1.plot(poverty_vs.index, poverty_vs, color='#E6232E', linewidth=3, linestyle='--')
ax2.plot(graduation_vs.index, graduation_vs, color='skyblue', linewidth=3, marker='o')

twinx() = 「共用 X 轴、各自独立 Y 轴」。

⚠️ 「双轴图」是「数据可视化里公认的「欺骗性图表」」:

两条线的「相对高低」完全由「两个 Y 轴的缩放」决定——你可以调参数让「任何两条线看起来同步」。

「两条线一起涨」不代表「它们相关」——要证明相关,应该画「散点图 + 回归」(cell 49/51 就做了,这才是正解)。

⚠️ 另外 poverty_vs.index 和 graduation_vs.index 都是「州名字符串」——matplotlib 会「按首次出现顺序」排,不是「字母序」——两条线的 X 轴可能「错位」。

(10)cell 49 / 51 / 52:三种「相关」的画法

1
2
3
sns.jointplot(x='poverty_rate', y='percent_completed_hs', data=merged, kind='kde')
sns.lmplot(x='poverty_rate', y='percent_completed_hs', data=merged)
sns.regplot(x='poverty_rate', y='percent_completed_hs', data=merged)
函数 画什么
jointplot(kind='kde')散点 + 边缘分布 + 二维密度等高线
lmplot散点 + 回归线 + 95% 置信带(Figure 级,能 hue/row/col 分面)
regplot同上,但「Axes 级」(能塞进 subplots)

⚠️ lmplot 和 regplot 在这个数据上「几乎一模一样」——区别只在「能不能分面」。

⚠️ 而 merged 只有 51 行(50 个州 + DC)——51 个点的回归,p 值「很脆弱」。

(11)cell 57:五根柱子「叠在同一个位置」

1
2
3
4
5
6
for n in range(len(racial)):
plt.bar(racial.index[n], racial['share_white'][n], color=color_list[0])
plt.bar(racial.index[n], racial['share_black'][n], color=color_list[1])
plt.bar(racial.index[n], racial['share_native_american'][n], color=color_list[2])
plt.bar(racial.index[n], racial['share_asian'][n], color=color_list[10])
plt.bar(racial.index[n], racial['share_hispanic'][n], color=color_list[9])

⚠️ 真 bug:plt.bar 的 bottom 参数没传

五根柱子「起点都是 y=0」——所以「后画的盖住先画的」——最终只看得到「最后一个(hispanic)」。

「堆叠柱状图」必须「逐层累加 bottom」:

1
2
3
4
bottom = np.zeros(len(racial))
for col, color in zip(['share_white','share_black',...], color_list):
plt.bar(racial.index, racial[col], bottom=bottom, color=color, label=col)
bottom += racial[col].values

⚠️ 而 color_list[10] 和 color_list[9] 是「随便挑的」——colors._colors_full_map 是一个「私有字典」,顺序「不保证稳定」——换个 matplotlib 版本,颜色就变了。

(12)cell 60:make_autopct —— 一个「漂亮的闭包」

1
2
3
4
5
6
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
return '{p:.2f}% ({v:d})'.format(p=pct, v=val)
return my_autopct

这是「让饼图同时显示「百分比 + 绝对数」」的标准技巧——值得记住。

为什么「不能直接」? 因为autopct 回调「只拿到百分比」,拿不到「原始计数」——所以要用「闭包」把 values 存进去。

⚠️ 但 values 是「整个 Series」——sum(values) 每次都被重算(N 个扇区算 N 次)——数据量大时应该「先算好 total」。

(13)cell 60 后半:甜甜圈的画法

1
2
3
my_circle = plt.Circle((0, 0), 0.7, color='white')
p = plt.gcf()
p.gca().add_artist(my_circle)

「在饼图中间盖一个白色圆」= 甜甜圈——plt.Circle((x, y), 半径, color=)。

⚠️ add_artist 是「必须的」——直接 plt.Circle(...) 不会「自动加进图里」。

⚠️ 这个白圆「会盖住」pctdistance=1.4 之外的标签吗? 不会(标签在半径 1.4 处,白圆半径 0.7)——但如果「圆画在最后」,它也可能盖住「饼图的边」。

(14)cell 65–66:age 填 0 之后的箱线图

1
2
df_fatalities['age'] = df_fatalities['age'].replace(np.nan, 0)
sns.boxplot(x='age', y='manner_of_death', hue='gender', data=death_age)

⚠️ 「年龄缺失填 0」= 「凭空造出一批「0 岁死者」」——箱线图的「最小值」会被「拉到 0」,中位数被「往下拽」。

正确做法:dropna(subset=['age'])(只丢「年龄缺失」那几十行,其他列照用)。

⚠️ 而且 x='age', y='manner_of_death' 是「反的」:习惯上「分类变量在 X、数值在 Y」——seaborn 会自动「按类型判断方向」,所以「能画出来」,但「读图的人会「先看 X 再看 Y」,容易误解。

(15)cell 69:60 种武器「重分类」——但把 undetermined 算成「有武器」

1
2
weapons = ['gun', 'toy weapon', 'nail gun', 'knife', ..., 'undetermined', ..., 'unknown weapon', ...]
armed.armed = armed.armed.replace(weapons, 'armed')

目标:把「60 多种具体武器」压成「armed / unarmed」两类。

⚠️ 但 weapons 列表里「混进了两个不该算的」:

值 该算成 代码算成
undetermined「不确定」armed(有武器) ❌
unknown weapon「不确定」armed(有武器) ❌

后果:「持械比例」被「系统性高估」——而这两个值恰好是「信息缺失」的那批。

⚠️ 而且「toy weapon 算 armed」也有争议:玩具枪「不是武器」,但「警察以为是武器」——这个数据集的「armed」本意是「警察当时认为他有武器」——所以「算 armed」在「分析警察决策」的语境下是对的(但在「分析实际危险性」的语境下是错的)。

「同一个字段,在不同问题下含义不同」——这是数据分析里「最需要写清楚」的事。

(16)cell 76:under / over * 100 —— 分母错了

1
2
3
4
5
junior = df_fatalities.loc[df_fatalities['age'] < 25]
under = junior.id.count()
senior = df_fatalities.loc[df_fatalities['age'] > 25]
over = senior.id.count()
print(f"{round((under / over) * 100)}% of people killed were under 25 years old.")

要算「25 岁以下占多少」——分母应该是「总人数」。

代码用了 under / over——这是「25 岁以下 : 25 岁以上」的「比值」,不是「占比」。

举例:1000 个死者里 200 个 <25、800 个 >25——真实占比 20%;代码算 200/800 = 25%——偏高 5 个百分点。

⚠️ 而且「年龄 = 0」(填进去的缺失值)会「全部算进 <25」——这会「进一步虚高」。

正确写法:

1
2
3
under = (df_fatalities['age'] < 25).sum()
total = df_fatalities['age'].notna().sum()
print(f"{under/total:.1%}")

⚠️ 还有「正好 25 岁」的人「两个条件都不满足」——被「静默丢掉」——加起来不等于 100%。

(17)cell 90 / 92:把「Index」当「label」

1
plt.bar(cities.index, cities, label=cities.index)

label= 期望「一个字符串」——这里传了「10 个城市名的 Index」——plt.legend() 会「画出 10 个图例项」或「报错」。

cell 92 更明显:

1
2
3
4
for c in cities.index:
...
plt.legend(loc='best')
plt.show()

「每个城市画一张图、每张图都加一次图例、每张图都 show()」——10 张图弹 10 次。

(18)cell 95:fig.show("png")

1
2
3
4
5
6
7
8
9
fig = go.Figure(data=go.Choropleth(
locations=states_to_map.index,
z=states_to_map,
locationmode='USA-states',
colorscale='Reds',
colorbar_title="Police Killings",
))
fig.update_layout(title_text='Police Killings by US State', geo_scope='usa')
fig.show("png")

locationmode='USA-states' + locations 传「两字母州缩写」——这是 Plotly 画美国州地图的正确用法。

⚠️ fig.show("png") 需要 kaleido(或老的 orca)——没装会「静默失败」或报错。

⚠️ 而且 z = states_to_map(一个 Series)——Plotly 接受 Series,但「索引顺序」和 locations 必须「完全对齐」——这里两者「同源」,所以安全。

(19)cell 97:infer_datetime_format 已被弃用

1
2
monthly_fatalities.date = pd.to_datetime(monthly_fatalities.date, infer_datetime_format=True).dt.to_period('m')
monthly_fatalities.date = monthly_fatalities.date.astype(str)

infer_datetime_format=True 在 pandas 2.0「弃用」、3.0「移除」——现在写了会「警告」或「报错」。

to_period('m') → astype(str):把日期变成 "2015-01" 这样的「月份标签」——方便后续 groupby 和「按字符串排序」。

⚠️ 但 to_period('m') 后「直接 astype(str)」会「丢掉时区/时间」——这里没时区,所以安全。

(20)cell 99:60 个 X 刻度

1
2
plt.plot(history.index, history, linewidth=3)
plt.xticks(ticks=history.index, fontsize=10, rotation=65)

63 个月份(2015-01 ~ 2020-05)「每个都当刻度」——旋转 65 度「还是挤」。

应该「每隔 6 个月显示一个」:

1
plt.xticks(ticks=history.index[::6])

这份 notebook 的问题

  1. cell 3 全是 Colab 专属命令(!wget/!apt-get,本地跑不了)。
  2. orca 已停维护(应 kaleido)。
  3. Counter / random 导入了没用。
  4. 「收入缺失填 0」会「系统性低估」。
  5. .isnull().any().sum() 只能答「有没有」,不能答「有几个」。
  6. 四张普查表是「按城市」的,却「按州 mean()」——未加权,指标定义错。
  7. plt.style.use('seaborn-deep') 在 matplotlib 3.6+ 已移除。
  8. 一根一根画柱子 + 循环里设刻度(慢且乱)。
  9. 双 Y 轴「制造虚假相关」(且 X 轴可能错位)。
  10. 五根柱子没传 bottom → 只剩最后一根可见。
  11. colors._colors_full_map 是私有 API(顺序不稳)。
  12. age 缺失填 0 → 箱线图/直方图「凭空多出一批 0 岁」。
  13. undetermined / unknown weapon 被算成 armed(持械率虚高)。
  14. under/over*100 分母错(不是占比)。
  15. 「正好 25 岁」被丢掉(加起来不等于 100%)。
  16. label=cities.index(图例坏掉)。
  17. cell 92 每城一图、每图一 show()(弹 10 次窗)。
  18. infer_datetime_format 已弃用。
  19. 60+ 个 X 刻度(不可读)。

README.md(10 行)

标题 Day 99 - Analyzing Deaths Involving Police in the United States,知识点四条:

  • Removing NaN Values and Duplicates
  • Create Pie and Donut Charts
  • Grouped Bar Charts and Box Plots with Plotly
  • Data Cleaning: Working with Time Stamps

⚠️ 第二条「Grouped Bar Charts and Box Plots with Plotly」是「Day 98 的清单抄过来的」——本 notebook 的箱线图是 sns.boxplot(Seaborn),不是 Plotly;「分组柱状图」也没出现(只有「叠在一起」的柱子和饼图)。

README 的四条里,只有第 1 条和第 4 条「名副其实」。

这一天真正的教学价值,在「三个反面教材」:

反面教材 教训
「州贫困率 = 各城市贫困率的平均」聚合前先问「一行代表什么」
「年龄缺失填 0」「0」是「一个真实取值」,不是「没有值」
「双 Y 轴看起来相关」相关要靠「散点 + 回归」,不靠「两条线」

「这三条,比「学会 px.sunburst」重要得多」——因为「图能画出来」只是「最低要求」,「结论站得住」才是「分析的终点」。

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