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

Python 100 天 · 第 78 天:诺贝尔奖数据:三种图表库总动员

这是「Python 100 天」系列第 78 天的学习笔记:诺贝尔奖数据:三种图表库总动员。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

一份 1901–2020 年的诺贝尔奖数据(获奖者、国家、机构、性别、奖金份额),要回答:女性获奖比例多少?哪个国家拿奖最多?哪些机构最集中?奖金是几人分?README 知识点:清洗数据、Plotly 柱状图与环形图、Matplotlib 看时间趋势、choropleth 地图、sunburst 旭日图。

这一天是"可视化选型"的实战:同一份数据,用三种库画出不同角度的图。

一、清洗:先分清"哪种缺失是正常的"

1
2
3
4
df_data.isna().sum()

col_subset = ['year','category','laureate_type','birth_date','full_name','organization_name']
df_data.loc[df_data.birth_date.isna()][col_subset]

缺失值不一定要删。这里:

  • birth_date 缺失的都是"组织获奖"(laureate_type == 'Organization'),本来就没有生日;
  • organization_name 缺失的是"个人获奖且没填机构"。

所以不能 dropna(),那会把所有组织获奖记录删掉。正确做法是"按类型分别处理",或在使用某列时再过滤。

这是这一天最重要的判断:isna().any() 告诉你"有没有",isna().sum() 告诉你"每列多少",loc[条件][列子集] 告诉你"缺的是哪些行"——三步定位,再决定删还是留。

二、拆字符串算比例

1
2
3
4
separated_values = df_data.prize_share.str.split('/', expand=True)   # "1/3" → ["1","3"]
numerator = pd.to_numeric(separated_values[0])
denomenator = pd.to_numeric(separated_values[1])
df_data['share_pct'] = numerator / denomenator

"1/3" 这种"分数形式的字符串"必须拆开才能算。str.split('/', expand=True) 拆成两列,分别转数字,再相除。

注意变量名拼错:denomenator(应为 denominator)。不影响运行,但读代码的人会愣一下。

三、找"多次获奖的人"

1
2
is_winner = df_data.duplicated(subset=['full_name'], keep=False)
multiple_winners = df_data[is_winner]

duplicated(keep=False) 把所有重复项都标记为 True(默认 keep='first' 只标记后面的)。然后用 nunique() 数"有多少个不同的人"。

另一种写法:

1
df_data.groupby('full_name').filter(lambda x: len(x) >= 2)

groupby().filter() 按组筛选,返回原表结构——比 duplicated 更灵活(可以按任意组内条件筛)。

四、Plotly 环形图看性别

1
2
3
4
5
biology = df_data.sex.value_counts()
fig = px.pie(labels=biology.index, values=biology.values,
names=biology.index, hole=0.4,
title="Percentage of Male vs. Female Winners")
fig.update_traces(textposition='inside', textfont_size=15, textinfo='percent')

value_counts() 直接喂饼图。hole=0.4 变环形。

五、Choropleth 地图

1
2
3
fig = px.choropleth(df_country, locations='country', locationmode='country names',
color='count', hover_name='country',
color_continuous_scale='agsunset')
  • locations 是国家名/ISO 码;
  • locationmode='country names' 表示"用英文国名匹配"(也可以用 'ISO-3');
  • color 决定颜色深浅。

国家名必须和 Plotly 内置的一致("United States" 不是 "USA"),否则那个国家不上色——地图上少一块是最常见的坑。

六、Sunburst 旭日图

1
fig = px.sunburst(df_data, path=['continent', 'country', 'organization_name'], values='share_pct')

path 是层级:大洲 → 国家 → 机构。内圈是大洲,点一下钻进去看国家,再点看机构。这是"三层分类占比"最好用的图,比三张饼图清晰得多。

代码全文(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
486
487
488
489
490
491
492
493
# 魔法命令:在 notebook 里装/升级 plotly。%pip 只在 Jupyter 有效,脚本里要用 pip 命令行。
# %pip install --upgrade plotly

# 五个库一起导入:pandas 表格、numpy 数组、plotly 交互图、seaborn 统计图、matplotlib 基础图。
import pandas as pd
import numpy as np
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt

# 全局浮点显示两位小数,后面的占比列才好看。
pd.options.display.float_format = '{:,.2f}'.format

# 诺奖数据:1901-2016 的获奖者,一行一个“人-奖项”组合。
df_data = pd.read_csv('nobel_prize_data.csv')

# shape:约千行、十几列,规模不大可以全量分析。
df_data.shape

# head() 看列名:year/category/prize/sex/birth_date/birth_country/.../prize_share。
df_data.head()

# tail():最近的年份。
df_data.tail()

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

# isna():逐格判断是否缺失,.values 转 numpy、.any() 汇总成“有没有”。
print(f'Any NaN values among the data? {df_data.isna().values.any()}')

# isna().sum():按列统计缺失个数 —— 定位哪几列有空洞。
df_data.isna().sum()

# 只看 birth_date 为空的行(限定几列避免屏幕刷爆):
# 这些人多是机构获奖(如“红十字国际委员会”),本来就没有出生日期,属于结构性缺失而不是脏数据。
# NaN values for birth date are all organisations
col_subset = ['year','category', 'laureate_type',
'birth_date','full_name', 'organization_name']
df_data.loc[df_data.birth_date.isna()][col_subset]

# 同理 organization_name 为空的行,也许是非机构获奖者,需要具体看。
# NaN values for organisation_name
col_subset = ['year','category', 'laureate_type','full_name', 'organization_name']
df_data.loc[df_data.organization_name.isna()][col_subset]

# 把 birth_date 从字符串转成 datetime,后面才能取 .dt.year。
df_data.birth_date = pd.to_datetime(df_data.birth_date)

# prize_share 形如 '1/3':
# .str.split('/', expand=True) 拆成两列(分子、分母);
# pd.to_numeric 转数字;
# 相除得到“这一位获奖者占该奖项的百分比”。
# 注意:一位获奖者拿 1/3,则同年 3 人共享该奖。
separated_values = df_data.prize_share.str.split('/', expand=True)
numerator = pd.to_numeric(separated_values[0])
denomenator = pd.to_numeric(separated_values[1])
df_data['share_pct'] = numerator / denomenator

# info():确认新列 share_pct 是 float,且各列类型都对。
df_data.info()

# 性别分布环形图。px.pie 里 labels 与 names 是同一份数据的两种叫法,
# 新版 plotly 只认 names,同时传 labels 会告警但不影响显示(原码保留)。
# hole=0.4 挖空成环,update_traces 控制标签位置与文字内容。
biology = df_data.sex.value_counts()
fig = px.pie(labels=biology.index,
values=biology.values,
title="Percentage of Male vs. Female Winners",
names=biology.index,
hole=0.4,)

fig.update_traces(textposition='inside', textfont_size=15, textinfo='percent')

fig.show()

# 按年份升序看最早的 3 位女性获奖者(1903 年的居里夫人就在其中)。
df_data[df_data.sex == 'Female'].sort_values('year', ascending=True)[:3]

# duplicated(subset=['full_name'], keep=False):**所有**出现过两次及以上的行都标记 True;
# keep=False 是关键 —— 默认 keep='first' 只留重复行中的第一条。
# nunique() 数“有多少个不同的人”重复获奖。
is_winner = df_data.duplicated(subset=['full_name'], keep=False)
multiple_winners = df_data[is_winner]
print(f'There are {multiple_winners.full_name.nunique()}'
' winners who weere awarded the prize more than once.')

# 等价写法:groupby 后 filter,保留“获奖次数 >= 2”的整组。
# Alternative:
multiple_winners = df_data.groupby(by = 'full_name').filter(lambda x : x['year'].count() >= 2)

# 限定列看这些重复获奖者的明细。
col_subset = ['year', 'category', 'laureate_type', 'full_name']
multiple_winners[col_subset]

# 有多少个奖项大类(物理、化学、医学、文学、和平、经济)。
# Number of different categories
df_data.category.nunique()

# 各大类的奖项数柱状图;color 用同一个数量做渐变,coloraxis_showscale=False 隐藏色条。
prizes_per_category = df_data.category.value_counts()
v_bar = px.bar(
x = prizes_per_category.index,
y = prizes_per_category.values,
color = prizes_per_category.values,
color_continuous_scale='Aggrnyl',
title='Number of Prizes Awarded per Category')

v_bar.update_layout(xaxis_title='Nobel Prize Category',
coloraxis_showscale=False,
yaxis_title='Number of Prizes')
v_bar.show()

# 经济学奖是 1969 年才设立的 —— 看它最早的 3 条记录验证这一点。
df_data[df_data.category == 'Economics'].sort_values('year')[:3]

# 按“大类 × 性别”分组计数,as_index=False 让分组键保留为普通列,方便直接画图。
cat_men_women = df_data.groupby(['category', 'sex'],
as_index=False).agg({'prize': pd.Series.count})
cat_men_women.sort_values('prize', ascending=False, inplace=True)
cat_men_women

# 分组柱状图:color=sex 自动按性别并排/堆叠,一眼看出男女比例悬殊。
v_bar_split = px.bar(x = cat_men_women.category,
y = cat_men_women.prize,
color = cat_men_women.sex,
title='Number of Prizes Awarded per Category split by Men and Women')

v_bar_split.update_layout(xaxis_title='Nobel Prize Category',
yaxis_title='Number of Prizes')
v_bar_split.show()

# 每年颁奖数量:groupby('year').count().prize 取 prize 列(每行一条奖项记录)。
prize_per_year = df_data.groupby(by='year').count().prize

# rolling(window=5).mean():5 年移动平均,把年度波动抹平看趋势。
# 前 4 个值是 NaN(窗口不足),画线时会自动断开。
moving_average = prize_per_year.rolling(window=5).mean()

# 散点是每年真实值,红线是移动平均 —— 同图叠加以保留细节又看清趋势。
# s=100 点大小,alpha=0.7 半透明防重叠。
plt.scatter(x=prize_per_year.index,
y=prize_per_year.values,
c='dodgerblue',
alpha=0.7,
s=100,)

plt.plot(prize_per_year.index,
moving_average.values,
c='crimson',
linewidth=3,)

plt.show()

# 美化版:figsize 16×8、dpi=200 出印刷级图;
# plt.xticks(ticks=np.arange(1900,2021,step=5)) 指定刻度位置;
# ax.set_xlim(1900,2020) 限定可视范围。
plt.figure(figsize=(16,8), dpi=200)
plt.title('Number of Nobel Prizes Awarded per Year', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(ticks=np.arange(1900, 2021, step=5),
fontsize=14,
rotation=45)

ax = plt.gca()
ax.set_xlim(1900, 2020)

ax.scatter(x=prize_per_year.index,
y=prize_per_year.values,
c='dodgerblue',
alpha=0.7,
s=100,)

ax.plot(prize_per_year.index,
moving_average.values,
c='crimson',
linewidth=3,)

plt.show()

# 每年“平均获奖份额”的 5 年移动平均 —— 份额下降说明共享奖项的人变多了。
yearly_avg_share = df_data.groupby(by='year').agg({'share_pct': pd.Series.mean})
share_moving_average = yearly_avg_share.rolling(window=5).mean()

# 双轴:左轴奖项数量、右轴平均份额,两条移动平均线放一起对比趋势。
plt.figure(figsize=(16,8), dpi=200)
plt.title('Number of Nobel Prizes Awarded per Year', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(ticks=np.arange(1900, 2021, step=5),
fontsize=14,
rotation=45)

ax1 = plt.gca()
ax2 = ax1.twinx() # create second y-axis
ax1.set_xlim(1900, 2020)

ax1.scatter(x=prize_per_year.index,
y=prize_per_year.values,
c='dodgerblue',
alpha=0.7,
s=100,)

ax1.plot(prize_per_year.index,
moving_average.values,
c='crimson',
linewidth=3,)

# Adding prize share plot on second axis
ax2.plot(prize_per_year.index,
share_moving_average.values,
c='grey',
linewidth=3,)

plt.show()

# ax2.invert_yaxis():把右轴**上下翻转**。
# 因为份额越小代表“共享的人越多”,翻转后两条线的同向变化才直观。
plt.figure(figsize=(16,8), dpi=200)
plt.title('Number of Nobel Prizes Awarded per Year', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(ticks=np.arange(1900, 2021, step=5),
fontsize=14,
rotation=45)

ax1 = plt.gca()
ax2 = ax1.twinx()
ax1.set_xlim(1900, 2020)

# Can invert axis
ax2.invert_yaxis()

ax1.scatter(x=prize_per_year.index,
y=prize_per_year.values,
c='dodgerblue',
alpha=0.7,
s=100,)

ax1.plot(prize_per_year.index,
moving_average.values,
c='crimson',
linewidth=3,)

ax2.plot(prize_per_year.index,
share_moving_average.values,
c='grey',
linewidth=3,)

plt.show()

# 按出生国统计获奖数;先升序排,再取 [-20:] 得到最多的 20 个国家。
# 注意 [-20:] 是“最后 20 行”,依赖前面的排序,顺序不能颠倒。
top_countries = df_data.groupby(['birth_country_current'],
as_index=False).agg({'prize': pd.Series.count})

top_countries.sort_values(by='prize', inplace=True)
top20_countries = top_countries[-20:]
top20_countries

# 横向条形图:x 是数量、y 是国家名,orientation='h' 才是横的。
h_bar = px.bar(x=top20_countries.prize,
y=top20_countries.birth_country_current,
orientation='h',
color=top20_countries.prize,
color_continuous_scale='Viridis',
title='Top 20 Countries by Number of Prizes')

h_bar.update_layout(xaxis_title='Number of Prizes',
yaxis_title='Country',
coloraxis_showscale=False)
h_bar.show()

# 带上 ISO 国家代码(choropleth 需要它来定位国家)。
df_countries = df_data.groupby(['birth_country_current', 'ISO'],
as_index=False).agg({'prize': pd.Series.count})
df_countries.sort_values('prize', ascending=False)

# px.choropleth:世界地图着色。locations 传 ISO-3 代码,color 决定颜色深浅。
# color_continuous_scale 用 plotly 内置色系 px.colors.sequential.matter。
world_map = px.choropleth(df_countries,
locations='ISO',
color='prize',
hover_name='birth_country_current',
color_continuous_scale=px.colors.sequential.matter)

world_map.update_layout(coloraxis_showscale=True,)

world_map.show()

# “国家 × 类别”的获奖数,为下一张堆叠图准备。
cat_country = df_data.groupby(['birth_country_current', 'category'],
as_index=False).agg({'prize': pd.Series.count})
cat_country.sort_values(by='prize', ascending=False, inplace=True)
cat_country

# merge 后再直接改 columns:**按位置**赋名,依赖 merge 后的列顺序(cat_prize 在前、total_prize 在后),
# 属于能跑但脆弱的写法;更稳的是 merge 时用 suffixes 或 rename。
merged_df = pd.merge(cat_country, top20_countries, on='birth_country_current')
# change column names
merged_df.columns = ['birth_country_current', 'category', 'cat_prize', 'total_prize']
merged_df.sort_values(by='total_prize', inplace=True)
merged_df

# 横向堆叠条形图:同一个国家按类别分段,能看出该国的强项学科。
cat_cntry_bar = px.bar(x=merged_df.cat_prize,
y=merged_df.birth_country_current,
color=merged_df.category,
orientation='h',
title='Top 20 Countries by Number of Prizes and Category')

cat_cntry_bar.update_layout(xaxis_title='Number of Prizes',
yaxis_title='Country')
cat_cntry_bar.show()

# 按“国家 × 年份”统计每年获奖数,并只保留三列。
prize_by_year = df_data.groupby(by=['birth_country_current', 'year'], as_index=False).count()
prize_by_year = prize_by_year.sort_values('year')[['year', 'birth_country_current', 'prize']]
prize_by_year

# 累积曲线:groupby(...).sum() 先合并同国同年,
# 再 .groupby(level=[0]).cumsum() 按国家(第 0 层索引)做累计求和;
# reset_index() 把多级索引还原成列,才能给 plotly 用。
cumulative_prizes = prize_by_year.groupby(by=['birth_country_current',
'year']).sum().groupby(level=[0]).cumsum()
cumulative_prizes.reset_index(inplace=True)

# 多线图:每个国家一条累积曲线,hover 显示国名。
l_chart = px.line(cumulative_prizes,
x='year',
y='prize',
color='birth_country_current',
hover_name='birth_country_current')

l_chart.update_layout(xaxis_title='Year',
yaxis_title='Number of Prizes')

l_chart.show()

# 机构获奖数前 20,再升序排(横向条形图从上到下由少到多)。
top20_orgs = df_data.organization_name.value_counts()[:20]
top20_orgs.sort_values(ascending=True, inplace=True)

# 研究机构排名横向条形图。
org_bar = px.bar(x = top20_orgs.values,
y = top20_orgs.index,
orientation='h',
color=top20_orgs.values,
color_continuous_scale=px.colors.sequential.haline,
title='Top 20 Research Institutions by Number of Prizes')

org_bar.update_layout(xaxis_title='Number of Prizes',
yaxis_title='Institution',
coloraxis_showscale=False)
org_bar.show()

# 机构所在城市排名(换个口径看科研地理分布)。
top20_org_cities = df_data.organization_city.value_counts()[:20]
top20_org_cities.sort_values(ascending=True, inplace=True)
city_bar2 = px.bar(x = top20_org_cities.values,
y = top20_org_cities.index,
orientation='h',
color=top20_org_cities.values,
color_continuous_scale=px.colors.sequential.Plasma,
title='Which Cities Do the Most Research?')

city_bar2.update_layout(xaxis_title='Number of Prizes',
yaxis_title='City',
coloraxis_showscale=False)
city_bar2.show()

# 获奖者出生城市排名。
top20_cities = df_data.birth_city.value_counts()[:20]
top20_cities.sort_values(ascending=True, inplace=True)
city_bar = px.bar(x=top20_cities.values,
y=top20_cities.index,
orientation='h',
color=top20_cities.values,
color_continuous_scale=px.colors.sequential.Plasma,
title='Where were the Nobel Laureates Born?')

city_bar.update_layout(xaxis_title='Number of Prizes',
yaxis_title='City of Birth',
coloraxis_showscale=False)
city_bar.show()

# 三级分组:机构国家 → 城市 → 机构名,为旭日图准备层级数据。
country_city_org = df_data.groupby(by=['organization_country',
'organization_city',
'organization_name'], as_index=False).agg({'prize': pd.Series.count})

country_city_org = country_city_org.sort_values('prize', ascending=False)
country_city_org

# px.sunburst:旭日图/同心环,path 是从外到内的层级,values 决定扇形大小。
burst = px.sunburst(country_city_org,
path=['organization_country', 'organization_city', 'organization_name'],
values='prize',
title='Where do Discoveries Take Place?',
)

burst.update_layout(xaxis_title='Number of Prizes',
yaxis_title='City',
coloraxis_showscale=False)

burst.show()

# .dt.year:从 datetime 列取出年份(Series.dt 访问器)。
# Use Datetime object
birth_years = df_data.birth_date.dt.year
birth_years

# 获奖年龄 = 获奖年 - 出生年。
# 注意缺失出生日期的行结果是 NaN,会从统计里自动排除。
df_data['winning_age'] = df_data.year - birth_years
df_data.winning_age

# nlargest/nsmallest(n=1, columns=...):直接取某列最大/最小的那一行。
# display() 是 IPython 内置函数,只在 notebook 里可用(脚本里用 print)。
display(df_data.nlargest(n=1, columns='winning_age'))
display(df_data.nsmallest(n=1, columns='winning_age'))

# describe():年龄的均值、分位数、极值 —— 最年轻的获奖者只有 17 岁。
df_data.winning_age.describe()

# histplot(bins=30):直方图看年龄分布形状。
plt.figure(figsize=(8, 4), dpi=200)
sns.histplot(data=df_data,
x=df_data.winning_age,
bins=30)
plt.xlabel('Age')
plt.title('Distribution of Age on Receipt of Prize')
plt.show()

# regplot(lowess=True):不假设线性,用局部加权回归画出“随年份变化的趋势曲线”,
# 比一条直线更能反映“获奖者越来越老”这种非线性趋势。
plt.figure(figsize=(8,4), dpi=200)
with sns.axes_style("whitegrid"):
sns.regplot(data=df_data,
x='year',
y='winning_age',
lowess=True,
scatter_kws = {'alpha': 0.4},
line_kws={'color': 'black'})

plt.show()

# 箱线图:按奖项类别看年龄分布差异(物理/化学偏老,和平奖跨度大)。
plt.figure(figsize=(8,4), dpi=200)
with sns.axes_style("whitegrid"):
sns.boxplot(data=df_data,
x='category',
y='winning_age')

plt.show()

# plotly 版箱线图,可交互悬停。
# Box plot using plotly instead
box = px.box(df_data,
x='category',
y='winning_age',
title='How old are the Winners?')

box.update_layout(xaxis_title='Category',
yaxis_title='Age at time of Award',
xaxis={'categoryorder':'mean ascending'},)

box.show()

# lmplot(row='category'):按类别**分行**画多个子图,每行一个类别。
# aspect=2 控制每个子图的宽高比。
with sns.axes_style('whitegrid'):
sns.lmplot(data=df_data,
x='year',
y='winning_age',
row = 'category',
lowess=True,
aspect=2,
scatter_kws = {'alpha': 0.6},
line_kws = {'color': 'black'},)

plt.show()

# 另一种布局:hue='category' 全部画在同一张图里,用颜色区分类别,便于横向比较。
with sns.axes_style("whitegrid"):
sns.lmplot(data=df_data,
x='year',
y='winning_age',
hue='category',
lowess=True,
aspect=2,
scatter_kws={'alpha': 0.5},
line_kws={'linewidth': 5})

plt.show()

走读与要点

  1. 顶部 # %pip install --upgrade plotly 是 Colab 的魔法命令(注释状态),本地跑要 pip install -U plotly。
  2. 五个库一起导入:pandas / numpy / plotly / seaborn / matplotlib。
  3. 体检:duplicated().any()、isna().any()、isna().sum()。
  4. df_data.loc[df_data.birth_date.isna()][col_subset]:限定列看缺失行,输出才读得懂。
  5. to_datetime(birth_date) → 之后能算获奖年龄。
  6. 拆 prize_share 得到 share_pct。
  7. 按性别画环形图;按年份画获奖人数趋势(Matplotlib);按国家画地图;按"大洲-国家-机构"画旭日图。

这份代码的问题

(1) prize_share 有 "1/1" 也有 "1/2"

"1/1" → 1.0,正确。但如果某行是 "1"(没有斜杠),split 后第二列为 NaN → 除法得 NaN。要检查 separated_values.shape[1] == 2。

(2) 组织获奖者的 sex 字段

组织没有性别,value_counts() 里可能出现空值或 "Organization",会污染"男女比例"的统计。应该先过滤 laureate_type == 'Individual'。

(3) 国家统计重复计数

一个人可能被记多次(多次获奖),"获奖人数"和"获奖次数"是两个指标。用 nunique() 还是 count() 要明确。

(4) 地图的国名不统一

历史国家(苏联、东德)在数据里可能是旧名,Plotly 不认,会留白。需要一张"旧名 → 新名"的映射表。

(5) 旭日图的 values 用 share_pct

这表示"按奖金份额加权",和"按人数"结果不同。用哪个取决于问题,但图注要写清楚。

运行结果

  • 性别环形图:女性约 6%,男性约 94%(1901–2020);
  • 时间趋势:女性获奖者集中在 1990 年之后;
  • 地图:美国、英国、德国、法国最深;
  • 旭日图:欧洲 → 英国/德国 → 具体大学,层级一目了然。

易错点

  1. 对组织获奖记录 dropna():数据量骤减,比例全错。
  2. px.choropleth 的 locations 用了中文国名:一片空白。
  3. path 里有 NaN:旭日图报错,要先 fillna('Unknown')。
  4. fig.show() 在 JupyterLab 里不显示:需要 plotly 的 labextension,或用 fig.write_html。

动手改

  • 过滤出个人获奖者,重画性别比例。
  • 算"获奖时的年龄"(year - birth_date.dt.year),画年龄分布。
  • 给旭日图的缺失机构填 'Unknown' 再看。

源文件逐个讲解

3 个文件:

文件 规模 职责
day78.ipynb99 个单元格诺贝尔奖 120 年数据:清洗、性别、国家、机构、年龄
nobel_prize_data.csv962 行 × 16 列1901–2020 全部诺奖得主
README.md8 行说明页

nobel_prize_data.csv——16 列

1
2
3
year,category,prize,motivation,prize_share,laureate_type,full_name,
birth_date,birth_city,birth_country,birth_country_current,sex,
organization_name,organization_city,organization_country,ISO

逐列看:

列 说明 坑
year颁奖年—
category6 个类别—
prize奖项全名—
motivation获奖理由(带引号,含逗号)超长文本
prize_share"1/1"、"1/2"、"1/3"字符串分数
laureate_typeIndividual / Organization—
full_name姓名有重复(多次获奖)
birth_date生日有 NaN(机构获奖)
birth_city / birth_country出生地—
birth_country_current现行国名和 birth_country 不同(历史国界变了)
sexMale / Female有 NaN(机构)
organization_name所属机构有 NaN(独立研究者)
organization_city / organization_country机构所在地—
ISO三字母国家码画地图必需

两个「三胞胎」要注意:

birth_country vs birth_country_current:前者是「当年」的国名(如 Prussia、Austria-Hungary),后者是「现在」的国名(如 Germany、Austria)。做国家统计必须用 current。

三个地名维度:出生地、机构所在地——「人才在哪出生」和「成果在哪产出」是两回事,这个区别贯穿全天。

day78.ipynb(99 个单元格)

(1)五个库

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

Plotly 画交互图(饼/柱/地图/旭日),Seaborn 画统计图(回归/箱线)。

(2)数据说明:三个日期是估算的

markdown 明确写了:

Michael Houghton、Venkatraman Ramakrishnan、Nadia Murad 的准确生日未知,用 7 月 2 日(年中)代替。

这是「数据诚实」的示范——作者主动交代了「哪些值不可信」。

(3)查缺失:按列统计

1
2
print(f'Any NaN values among the data? {df_data.isna().values.any()}')
df_data.isna().sum()

isna().sum() 给出每列的缺失数——数值差异很大:

  • birth_date / birth_city / sex:约 28~30 个(机构获奖)
  • organization_name:约 200+ 个(独立研究者)
  • motivation:0 个

(4)用「交叉列」验证 NaN 的原因

1
2
3
col_subset = ['year','category', 'laureate_type',
'birth_date','full_name', 'organization_name']
df_data.loc[df_data.birth_date.isna()][col_subset]
1
2
col_subset = ['year','category', 'laureate_type','full_name', 'organization_name']
df_data.loc[df_data.organization_name.isna()][col_subset]

两个查询,两个结论:

  1. birth_date 为空的,laureate_type 全是 Organization——机构没有生日;
  2. organization_name 为空的,laureate_type 全是 Individual——个人不一定有机构。

这是「NaN 不是错误,是语义」的经典案例——不该 dropna(),而应该「按类型分开处理」。

(5)分数转小数:两层 split

1
2
3
4
separated_values = df_data.prize_share.str.split('/', expand=True)
numerator = pd.to_numeric(separated_values[0])
denomenator = pd.to_numeric(separated_values[1])
df_data['share_pct'] = numerator / denomenator

"1/3" → 0.333 的三步:

  1. .str.split('/', expand=True) → 两列("1"、"3");
  2. 两列各自 to_numeric;
  3. 相除。

⚠️ denomenator 拼写错了(应为 denominator)——不影响运行,但变量名错别字会被后面的人误读。

prize_share 的含义:1/3 = 「三人分享此奖,我占三分之一」。

所以 share_pct 越小,说明「合作者越多」——这是「科学越来越靠团队」的量化证据。

(6)环形图:性别比例

1
2
3
4
5
6
7
biology = df_data.sex.value_counts()
fig = px.pie(labels=biology.index,
values=biology.values,
title="Percentage of Male vs. Female Winners",
names=biology.index,
hole=0.4,)
fig.update_traces(textposition='inside', textfont_size=15, textinfo='percent')

biology 这个变量名是笔误(应该是「biology 相关」的遗留)——实际存的是「性别计数」。

hole=0.4:环形图(中间挖掉 40% 半径,能放标题)。

结论:女性得主占比约 6%(截至 2020 年)——这个数字本身就是一个「值得追问」的发现。

(7)前三名女性得主

1
df_data[df_data.sex == 'Female'].sort_values('year', ascending=True)[:3]

sort_values('year', ascending=True)[:3]:按年升序,取前 3。

答案:Marie Curie(1903 物理)、Bertha von Suttner(1905 和平)、Selma Lagerlöf(1909 文学)。

markdown 追问的三点很有意思:

  • 她们拿了什么奖?(物理、和平、文学——横跨三个领域)
  • birth_country 是什么?(波兰/奥匈帝国/瑞典——当时的国界和现在不同)

(8)重复获奖者:keep=False

1
2
3
4
is_winner = df_data.duplicated(subset=['full_name'], keep=False)
multiple_winners = df_data[is_winner]
print(f'There are {multiple_winners.full_name.nunique()}'
' winners who weere awarded the prize more than once.')

duplicated(subset=['full_name'], keep=False) 是「标记所有重复项」的秘诀:

keep 行为
'first'(默认)只标记第 2 次及以后
'last'只标记第 1 次到倒数第 2 次
False所有出现过的都标记(第 1 次也标)

要「找出所有重复的人」必须用 keep=False——否则第一次获奖那次会被漏掉。

这是 duplicated 最容易被忽略的参数。

(9)第二种写法:groupby().filter()

1
multiple_winners = df_data.groupby(by = 'full_name').filter(lambda x : x['year'].count() >= 2)

filter 接收一个「返回布尔值的函数」,函数收到的是「每一组(子 DataFrame)」。

x['year'].count() >= 2:该组行数 ≥ 2。

两种思路对比:

方法 思路
duplicated(keep=False)「标记重复行」
groupby().filter()「筛出满足条件的组」

后者更通用(能写任意条件),前者更快。

(10)分类柱状图 + Aggrnyl

1
2
3
4
5
6
7
8
9
df_data.category.nunique()          # 6
prizes_per_category = df_data.category.value_counts()

v_bar = px.bar(
x = prizes_per_category.index,
y = prizes_per_category.values,
color = prizes_per_category.values,
color_continuous_scale='Aggrnyl',
title='Number of Prizes Awarded per Category')

color_continuous_scale='Aggrnyl':Plotly 内置的「连续色阶」(暗红→橙→黄)。

color=prizes_per_category.values + 连续色阶:柱子颜色深浅表示数量——「数值即颜色」。

注意这只是「装饰」——x 轴已经表示了分类,颜色只是加强视觉。

Aggrnyl 是知名色阶名(来自 cmocean 库的科学配色),Plotly 不区分大小写(Aggrnyl / aggrnyl 都行)。

(11)经济学奖:最晚设立

1
df_data[df_data.category == 'Economics'].sort_values('year')[:3]

结果:1969 年首次颁发(比其他五个奖项晚 68 年)。

原因:诺贝尔遗嘱里只有物理、化学、生理学或医学、文学、和平五个奖;经济学奖是 1968 年瑞典央行出资设立的「纪念奖」,严格说不是「诺贝尔奖」。

(12)按性别拆分的分组柱状图

1
2
3
4
5
6
7
8
cat_men_women = df_data.groupby(['category', 'sex'], 
as_index=False).agg({'prize': pd.Series.count})
cat_men_women.sort_values('prize', ascending=False, inplace=True)

v_bar_split = px.bar(x = cat_men_women.category,
y = cat_men_women.prize,
color = cat_men_women.sex,
title='Number of Prizes Awarded per Category split by Men and Women')

groupby(['category','sex']) + as_index=False:两列分组 → 分组键变普通列。

color=cat_men_women.sex:自动按性别分色 → 堆叠柱(Plotly px.bar 默认 barmode='relative' 是堆叠)。

⚠️ 这里漏了 barmode='group'——所以是「堆叠」而不是「并排」。

堆叠的问题:女性那一段太短(6%),几乎看不见。并排(group)更能看出差异。

.agg({'prize': pd.Series.count}) 里 prize 只是个「占位列」——数任何一列都行,因为每行就是一个奖。

(13)每年的获奖数 + 5 年滚动平均

1
2
prize_per_year = df_data.groupby(by='year').count().prize
moving_average = prize_per_year.rolling(window=5).mean()

groupby('year').count():每年多少行(= 多少个奖)。

.prize:从结果表里取 prize 这一列(因为每列计数都一样,随便取一列)。

rolling(window=5).mean():5 年滑动平均——把「某些年一次发 6 个、某些年发 3 个」的锯齿抹平。

为什么是 5 年? 因为诺奖每年 10 月颁一次,单年波动大;5 年 ≈ 「一个科研代际」,能看出趋势而不失细节。

(14)散点 + 折线:两层叠加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
plt.figure(figsize=(16,8), dpi=200)
plt.title('Number of Nobel Prizes Awarded per Year', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(ticks=np.arange(1900, 2021, step=5),
fontsize=14,
rotation=45)

ax = plt.gca()
ax.set_xlim(1900, 2020)

ax.scatter(x=prize_per_year.index,
y=prize_per_year.values,
c='dodgerblue',
alpha=0.7,
s=100)

ax.plot(prize_per_year.index,
moving_average.values,
c='crimson',
linewidth=3)

这张图的信息设计很聪明:

  • 点(scatter) = 真实值(有噪声);
  • 线(plot) = 滚动平均(趋势);
  • 两者叠加 = 「原始数据 + 平滑趋势」。

s=100:点的面积(不是半径)。 c='dodgerblue' / 'crimson':两个命名色。 plt.xticks(ticks=np.arange(1900,2021,5)):每 5 年一个刻度——手动控制刻度密度。

(15)双 y 轴:奖项数 + 分享比例

1
2
3
4
5
yearly_avg_share = df_data.groupby(by='year').agg({'share_pct': pd.Series.mean})
share_moving_average = yearly_avg_share.rolling(window=5).mean()

ax1 = plt.gca()
ax2 = ax1.twinx() # create second y-axis

左轴 = 「每年几个奖」,右轴 = 「平均分享比例」。

要回答的问题:「奖越颁越多,但是不是越来越多人分享?」

如果两条线反向走(奖数上升、分享比例下降)——说明「科学越来越靠大团队」。

(16)反转 y 轴

1
2
# Can invert ax
ax2.invert_yaxis()

invert_yaxis():y 轴上下翻转——大值在下、小值在上。

为什么反转? 因为share_pct 越小 = 「每人分得越少」= 「合作者越多」——反转后「线往上走」就等于「合作越来越多」,和直觉一致。

这是「让图表符合读者预期」的设计技巧。

(17)国家统计:groupby + 取后 20

1
2
3
4
5
top_countries = df_data.groupby(['birth_country_current'], 
as_index=False).agg({'prize': pd.Series.count})

top_countries.sort_values(by='prize', inplace=True)
top20_countries = top_countries[-20:]

[-20:] 取最后 20 行——因为前面按 prize 升序排过,最后 20 = 最多的 20 个。

为什么不用 nlargest(20, 'prize')? 因为后面画横柱图需要「升序」排列(最小值在底部)——先升序再切片,一步到位。

(18)国家三选一的问题

markdown 明确问了:

「用 birth_country、birth_country_current、还是 organization_country 最好?」

三个选项的语义完全不同:

列 回答的问题
birth_country「人才在哪出生」(但国名是历史的)
birth_country_current「人才出生地按现行国界算」(最常用于「国家排名」)
organization_country「成果在哪产出」

birth_country 的历史国名会碎成 Prussia、Austria-Hungary、USSR——这些国家现在不存在,排名会失真。

所以用 current——这是「数据口径」的重要一课。

(19)世界地图:choropleth

1
2
3
4
5
6
7
8
df_countries = df_data.groupby(['birth_country_current', 'ISO'], 
as_index=False).agg({'prize': pd.Series.count})

world_map = px.choropleth(df_countries,
locations='ISO',
color='prize',
hover_name='birth_country_current',
color_continuous_scale=px.colors.sequential.matter)

px.choropleth 三要素:

参数 作用
locations='ISO'国家标识(三字母码)
color='prize'填色依据
hover_name=鼠标悬停显示的标签

为什么必须 groupby(['国家','ISO']) 两列一起? 因为ISO 是「国家 → 代码」的映射,分组时带上它,每组才能拿到代码。

color_continuous_scale=px.colors.sequential.matter:Plotly 内置色阶集合(px.colors 下有 sequential、diverging、qualitative 三大类)。

(20)合并两张表做堆叠柱

1
2
3
4
5
6
cat_country = df_data.groupby(['birth_country_current', 'category'], 
as_index=False).agg({'prize': pd.Series.count})

merged_df = pd.merge(cat_country, top20_countries, on='birth_country_current')
merged_df.columns = ['birth_country_current', 'category', 'cat_prize', 'total_prize']
merged_df.sort_values(by='total_prize', inplace=True)

pd.merge(a, b, on='列名') = SQL 的 JOIN——默认 how='inner'(只保留两边都有的)。

merged_df.columns = [...] 直接改列名——因为 merge 后列名会带 _x/_y 后缀,不如手动重命名清晰。

四个新列名:

  • birth_country_current、category(分组键)
  • cat_prize:该国该类别获奖数
  • total_prize:该国总获奖数

(21)累计获奖数:groupby 套 cumsum

1
2
3
4
5
6
prize_by_year = df_data.groupby(by=['birth_country_current', 'year'], as_index=False).count()
prize_by_year = prize_by_year.sort_values('year')[['year', 'birth_country_current', 'prize']]

cumulative_prizes = prize_by_year.groupby(by=['birth_country_current',
'year']).sum().groupby(level=[0]).cumsum()
cumulative_prizes.reset_index(inplace=True)

这是全书最绕的一段链式操作,逐步拆:

① groupby(['国家','年']).count():每个(国家, 年)有多少奖。

② sort_values('year') + 选三列:按年排序(cumsum 必须按时间顺序才有意义)。

③ .groupby(['国家','年']).sum():把国家+年设为「双层索引」。

④ .groupby(level=[0]).cumsum():按「第 0 层索引(国家)」分组,做累计求和。

level=[0] 是「按索引层级分组」——不是按列。这是 MultiIndex 的专门语法。

⑤ reset_index():把索引还原成列——因为 px.line 需要 x='year' 是列。

结果:每个国家每年一行,prize 是「截至该年的累计获奖数」。

(22)折线图:多国累计

1
2
3
4
5
l_chart = px.line(cumulative_prizes,
x='year',
y='prize',
color='birth_country_current',
hover_name='birth_country_current')

color='国家':每个国家一条线——一键出「几十条曲线」。

这张图能直接回答:「美国什么时候超过德国?」(大约 1940 年代,二战前后)

(23)机构 / 城市排名:value_counts 直接用

1
2
3
4
5
top20_orgs = df_data.organization_name.value_counts()[:20]
top20_orgs.sort_values(ascending=True, inplace=True)

top20_org_cities = df_data.organization_city.value_counts()[:20]
top20_cities = df_data.birth_city.value_counts()[:20]

value_counts() 是「计数 + 排序」一体——比 groupby().count().sort_values() 短得多。

注意 value_counts() 默认自动排除 NaN——所以「没有机构」的人不会出现在机构榜里(正确行为)。

三个榜对比着看很有意思:

榜 第一名
机构University of California(各分校合并算)
机构城市Cambridge, MA(MIT + Harvard)
出生城市New York, NY

(24)旭日图:sunburst

1
2
3
4
5
6
7
8
country_city_org = df_data.groupby(by=['organization_country', 
'organization_city',
'organization_name'], as_index=False).agg({'prize': pd.Series.count})

burst = px.sunburst(country_city_org,
path=['organization_country', 'organization_city', 'organization_name'],
values='prize',
title='Where do Discoveries Take Place?')

px.sunburst 的三要素:

参数 含义
path=[列1, 列2, 列3]层级顺序(从内到外)
values='prize'每块大小
DataFrame每行是一条「叶子路径」

path 的三种层级:国家 → 城市 → 机构——越往里越细。

能点击:点「United States」扇区,整个图会只显示美国——这是 Plotly 的「下钻」交互。

(25)年龄:dt.year 两行搞定

1
2
birth_years = df_data.birth_date.dt.year
df_data['winning_age'] = df_data.year - birth_years

.dt 是「日期访问器」(类似 .str):

写法 取到
.dt.year年
.dt.month月
.dt.day日
.dt.dayofweek星期几(0=周一)

两行算出「获奖时年龄」——获奖年 - 出生年(不算月和日,是「大致年龄」)。

(26)最年长 / 最年轻

1
2
display(df_data.nlargest(n=1, columns='winning_age'))
display(df_data.nsmallest(n=1, columns='winning_age'))

nlargest / nsmallest:取最大/最小的 n 行——比 sort_values().head() 快(内部用堆)。

display() 是 Jupyter 专用函数——能在一个格子里打印多个 DataFrame(print 会把它们拼成文本)。

结果:

  • 最年轻:Lawrence Bragg,25 岁(1915 年物理奖,和父亲一起);
  • 最年长:John Goodenough,97 岁(2019 年化学奖,锂电池)。

(27)直方图:年龄分布

1
2
3
4
5
6
7
8
df_data.winning_age.describe()

plt.figure(figsize=(8, 4), dpi=200)
sns.histplot(data=df_data,
x=df_data.winning_age,
bins=30)
plt.xlabel('Age')
plt.title('Distribution of Age on Receipt of Prize')

sns.histplot(data=, x=, bins=30):bins=30 = 把年龄切成 30 个区间。

describe() 的关键数字:中位数约 60,均值约 59——诺奖是「老年人的奖」(因为要等成果被验证几十年)。

(28)年龄趋势:lowess

1
2
3
4
5
6
7
with sns.axes_style("whitegrid"):
sns.regplot(data=df_data,
x='year',
y='winning_age',
lowess=True,
scatter_kws = {'alpha': 0.4},
line_kws={'color': 'black'})

lowess=True:「局部加权散点平滑」(Locally Weighted Scatterplot Smoothing)——一条跟着数据弯的非直线。

和线性回归的区别:

方式 拟合
regplot 默认一条直线(强制线性)
lowess=True一条曲线(跟着数据走)

结论:获奖年龄随年代上升——「科学需要更长时间积累」。

lowess 在数据量大时很慢(O(n²)),962 行还好。

(29)分类箱线图

1
2
3
4
5
6
7
8
9
sns.boxplot(data=df_data,
x='category',
y='winning_age')

box = px.box(df_data,
x='category',
y='winning_age',
title='How old are the Winners?')
box.update_layout(xaxis={'categoryorder':'median descending'})

两种箱线图(Seaborn 静态 / Plotly 交互)——同一天画两遍,方便对比。

categoryorder='median descending':按各类中位数排序——一眼看出「哪个领域最年轻」。

结论:物理最年轻(理论突破早)、医学最年长(临床验证慢)。

(30)lmplot + row:六张小图

1
2
3
4
5
6
7
8
sns.lmplot(data=df_data,
x='year',
y='winning_age',
row = 'category',
lowess=True,
aspect=2,
scatter_kws = {'alpha': 0.6},
line_kws = {'color': 'black'},)

row='category':按类别「分行」画子图——6 个类别 = 6 行。

lmplot 和 regplot 的区别:

函数 特点
regplot画在「当前 axes」上(能和其他图叠加)
lmplot自己创建 Figure(支持 row/col/hue 分面)

aspect=2:每个子图宽高比 2:1。

(31)hue 版本

1
2
3
4
5
6
7
8
sns.lmplot(data=df_data,
x='year',
y='winning_age',
hue='category',
lowess=True,
aspect=2,
scatter_kws={'alpha': 0.5},
line_kws={'linewidth': 5})

row → hue 的切换:从「六张独立图」变成「一张图六条线」。

line_kws={'linewidth': 5}:线加粗(六条线叠在一张图上,细线会看不清)。

这是「同一份数据,两种布局」的对比:分面清晰但占空间,叠图紧凑但易混。

这份代码的问题

  1. denomenator 拼写错误(应为 denominator)。
  2. biology 变量名毫无意义(存的是性别计数)。
  3. px.bar 没设 barmode='group'(堆叠导致女性那段看不见)。
  4. df_data.year - birth_years 忽略了月日(年龄可能差 1 岁)。
  5. prize_per_year = groupby('year').count().prize:1970 年后有些年没颁奖(如 2018 年文学奖停颁)——count 会给出 0 行,图上有断点。
  6. top_countries[-20:] 依赖「已排序」这个隐含前提(如果中间插了一步操作就会错)。
  7. display() 是 Jupyter 专有(普通 Python 里未定义)。

README.md(8 行)

标题 Day 78 - Analysing the Nobel Prize with Plotly, Matplotlib and Seaborn,知识点:Plotly、Matplotlib、Seaborn、Choropleth Maps、Sunburst Charts。

五个:三个绘图库 + 地图 + 旭日图。

这一天是「可视化工具箱的大集合」:

图 回答什么问题
环形图性别比例
柱状图分类数量
折线图随时间的变化
地图(choropleth)地理分布
旭日图(sunburst)层级结构
箱线图分布对比
lmplot 分面分类趋势

七个图,七种「看数据的角度」——这是全书图表最密集的一天。

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