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

Python 100 天 · 第 74 天:时间序列:重采样、日期刻度与双轴

这是「Python 100 天」系列第 74 天的学习笔记:时间序列:重采样、日期刻度与双轴。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

三份 Google Trends 数据:特斯拉搜索量 vs 股价、比特币搜索量 vs 价格、美国失业金搜索量 vs 失业率。要看清"搜索热度"和"真实指标"是不是同步。README 知识点:数据探索、resample 重采样、折线图、日期刻度定位器与格式化器、线型与标记、网格、新数据的影响。

一、先把 MONTH 变成时间

1
2
type(df_tesla.MONTH[0])            # str
df_tesla.MONTH = pd.to_datetime(df_tesla.MONTH)

不转的话 resample 用不了、x 轴会当成字符串。时间序列分析的第一步永远是 to_datetime。

二、resample:把日数据变成月数据

1
df_btc_monthly = df_btc_price.resample('M', on='DATE').last()
  • 'M' 按月分组(还有 'W' 周、'Q' 季、'Y' 年、'D' 日);
  • on='DATE' 指定用哪一列当时间轴(如果索引已经是时间,就不用 on);
  • .last() 取每个月的最后一条记录。

聚合函数的选择很关键:价格取 last(月末收盘价)合理;取 mean 会磨平波动;取 max 是"月内最高"。同理搜索量是月度的,不能日对月直接比——必须先统一到同一时间粒度。

三、双 y 轴 + 日期刻度

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

ax1 = plt.gca()
ax2 = ax1.twinx()
ax1.plot(df_tesla.MONTH, df_tesla.TSLA_USD_CLOSE, color='#E6232E')
ax2.plot(df_tesla.MONTH, df_tesla.TSLA_WEB_SEARCH, color='skyblue')

ax1.xaxis.set_major_locator(years)
ax1.xaxis.set_major_formatter(years_fmt)
ax1.xaxis.set_minor_locator(months)
  • YearLocator 决定"主刻度每年一个";
  • MonthLocator 是次刻度(不写标签,只画小格);
  • DateFormatter('%Y') 把刻度显示成 2020 而不是完整时间戳。

不设 locator 时,Matplotlib 会自己挑刻度,经常出现 2020-01-01 2020-03-15 ... 这种挤在一起的丑标签。

四、线型、标记与网格

1
2
3
ax1.plot(x, y, color='#E6232E', linewidth=3)
ax2.plot(x, y, color='skyblue', linestyle='--', marker='o', markersize=4)
plt.grid(color='grey', linestyle='--', linewidth=0.5, alpha=0.5)
  • linestyle:'-' 实线、'--' 虚线、':' 点线、'-.' 点划线;
  • marker:'o' 圆点、'^' 三角、's' 方块;
  • alpha 透明度,网格线一定要低透明度,否则抢主体。

#E6232E 这种十六进制色比 'red' 好看得多,也更可控。

五、为什么要 register_matplotlib_converters()

1
2
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

旧版 pandas/matplotlib 之间对时间类型的处理不一致,会报一堆 MatplotlibDeprecationWarning。这行是"注册转换器",消掉警告。新版大多已内置,写了也不出错。

代码全文(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
# matplotlib.dates as mdates:专门处理时间轴的定位器(Locator)与格式化器(Formatter)。
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 一次读四个表:特斯拉搜索热度+股价、比特币搜索+价格、失业金搜索+失业率。
# 每个 read_csv 都返回一个 DataFrame,分别赋给变量。
df_tesla = pd.read_csv('TESLA Search Trend vs Price.csv')

df_btc_search = pd.read_csv('Bitcoin Search Trend.csv')
df_btc_price = pd.read_csv('Daily Bitcoin Price.csv')

df_unemployment = pd.read_csv('UE Benefits Search vs UE Rate 2004-19.csv')

# print(df.shape) + df.head():先看规模再看内容,避免一上来就 head 看不出问题。
print(df_tesla.shape)
df_tesla.head()

# Series.max() / min():极值。f-string 里直接嵌表达式,输出更可读。
print(f'Largest value for Tesla in Web Search: {df_tesla.TSLA_WEB_SEARCH.max()}')
print(f'Smallest value for Tesla in Web Search: {df_tesla.TSLA_WEB_SEARCH.min()}')

# describe():数值列的 count/mean/std/min/25%/50%/75%/max 八项统计,一次性体检。
df_tesla.describe()

# 失业金数据集:月度数据,2004-2019。
print(df_unemployment.shape)
df_unemployment.head()

# 字符串跨行拼接:相邻的两个字符串字面量会自动接起来,这里用来把长提示分行写。
print('Largest value for "Unemployemnt Benefits" '
f'in Web Search: {df_unemployment.UE_BENEFITS_WEB_SEARCH.max()}')

# 比特币价格是**日频**数据(每天一行),后面要重采样成月频才能和搜索热度对齐。
print(df_btc_price.shape)
df_btc_price.head()

# 比特币新闻搜索是月频。
print(df_btc_search.shape)
df_btc_search.head()

# 最大值:热度峰值出现在哪个月,后面会看到对应 2017 年底的暴涨。
print(f'largest BTC News Search: {df_btc_search.BTC_NEWS_SEARCH.max()}')

# isna().values.any():转 numpy 后判断“是否存在任意缺失”。
# 三个表都没有缺失(False = 没有 NaN)。
print(f'Missing values for Tesla?: {df_tesla.isna().values.any()}')
print(f'Missing values for U/E?: {df_unemployment.isna().values.any()}')
print(f'Missing values for BTC Search?: {df_btc_search.isna().values.any()}')

# 这里打印的是 BTC **搜索**表的缺失数,但从 df_btc_price 里筛 —— 提示文字和代码对不上,
# 属原码的复制粘贴笔误;要看价格表的空值应改成 df_btc_price.isna().values.sum()。
# 第二行专门挑出 CLOSE 为空的行,肉眼确认。
print(f'Missing values for BTC price?: {df_btc_search.isna().values.sum()}')
df_btc_price[df_btc_price.CLOSE.isna()]

# 这行只有一个字符串,没有表达式 —— 等于什么都没做(原码遗留)。
print(f'Number of missing values: ')

# dropna(inplace=True):直接丢掉含缺失的行,原地修改,返回 None。
df_btc_price.dropna(inplace=True)

# 检查 MONTH 列的类型:此时还是字符串(object),画时间轴前必须转 datetime。
type(df_tesla.MONTH[0])

# pd.to_datetime(列):字符串 → Timestamp。
# 四个表统一转换:月频表用 MONTH,日频价格表用 DATE。
# 只有真的 datetime 才能做 resample、时间刻度、日期运算。
df_tesla.MONTH = pd.to_datetime(df_tesla.MONTH)
df_btc_search.MONTH = pd.to_datetime(df_btc_search.MONTH)
df_unemployment.MONTH = pd.to_datetime(df_unemployment.MONTH)
df_btc_price.DATE = pd.to_datetime(df_btc_price.DATE)

# 转完看一眼:显示成 2010-01-01 这种日期格式。
df_tesla.MONTH.head()

# df.resample('M', on='DATE').last():按自然月末重采样('M'=MonthEnd)。
# on='DATE':指定用哪一列做时间轴(不设 DATE 为索引也能用);
# .last():每个月的“最后一个交易日的收盘价” —— 月内最高/最低都不如月末值适合代表当月;
# 其他常用:.mean() 月均、.sum() 月总、.first() 月初。
# 注意 'M' 在新版 pandas 里建议写 'ME'。
df_btc_monthly = df_btc_price.resample('M', on='DATE').last()

# 重采样后行数从“天”变成“月”,shape 可直接对比验证。
print(df_btc_monthly.shape)
df_btc_monthly.head()

# mdates.YearLocator():只在每年处打主刻度;MonthLocator() 打月份刻度;
# DateFormatter('%Y'):把刻度标签格式化成 4 位年份。
# 这三件套解决“日期标签挤成一团”的问题。
# Create locators for ticks on the time axis
years = mdates.YearLocator()
months = mdates.MonthLocator()
years_fmt = mdates.DateFormatter('%Y')

# register_matplotlib_converters():早期 pandas/matplotlib 版本需要注册日期转换器,
# 否则画时间轴会报 UserWarning。新版 matplotlib 已不再需要。
# Register date converters to avoid warning messages
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# 第一版双轴图:ax1 画股价(左轴),ax2 画搜索热度(右轴)。
# 没设颜色和字号 —— 后面几格逐步美化,这是教程的递进设计。
ax1 = plt.gca() # get current axis
ax2 = ax1.twinx()

ax1.set_ylabel('TSLA Stock Price')
ax2.set_ylabel('Search Trend')

ax1.plot(df_tesla.MONTH, df_tesla.TSLA_USD_CLOSE)
ax2.plot(df_tesla.MONTH, df_tesla.TSLA_WEB_SEARCH)

# 用 HEX 色值 '#E6232E'(特斯拉红)和具名色 'skyblue' 区分两条线,
# 并让 y 轴标签同色,读者一眼能配对。
ax1 = plt.gca()
ax2 = ax1.twinx()

ax1.set_ylabel('TSLA Stock Price', color='#E6232E') # can use a HEX code
ax2.set_ylabel('Search Trend', color='skyblue') # or a named colour

ax1.plot(df_tesla.MONTH, df_tesla.TSLA_USD_CLOSE, color='#E6232E')
ax2.plot(df_tesla.MONTH, df_tesla.TSLA_WEB_SEARCH, color='skyblue')

# figsize=(14,8), dpi=120:画布更大更清晰(像素 = 英寸 × dpi)。
# title(fontsize=18)、ylabel(fontsize=14)、linewidth 一起放大,避免高分辨率下字太小。
# increases size and resolution
plt.figure(figsize=(14,8), dpi=120)
plt.title('Tesla Web Search vs Price', fontsize=18)

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

# Also, increase fontsize and linewidth for larger charts
ax1.set_ylabel('TSLA Stock Price', color='#E6232E', fontsize=14)
ax2.set_ylabel('Search Trend', color='skyblue', fontsize=14)

ax1.plot(df_tesla.MONTH, df_tesla.TSLA_USD_CLOSE, color='#E6232E', linewidth=3)
ax2.plot(df_tesla.MONTH, df_tesla.TSLA_WEB_SEARCH, color='skyblue', linewidth=3)

# Displays chart explicitly
plt.show()

# plt.xticks(fontsize=14, rotation=45):x 轴标签旋转 45 度,防止日期重叠。
plt.figure(figsize=(14,8), dpi=120)
plt.title('Tesla Web Search vs Price', fontsize=18)

# Increase the size and rotate the labels on the x-axis
plt.xticks(fontsize=14, rotation=45)

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

ax1.set_ylabel('TSLA Stock Price', color='#E6232E', fontsize=14)
ax2.set_ylabel('Search Trend', color='skyblue', fontsize=14)

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

# Set the minimum and maximum values on the axes
ax1.set_ylim([0, 600])
ax1.set_xlim([df_tesla.MONTH.min(), df_tesla.MONTH.max()])

ax1.plot(df_tesla.MONTH, df_tesla.TSLA_USD_CLOSE, color='#E6232E', linewidth=3)
ax2.plot(df_tesla.MONTH, df_tesla.TSLA_WEB_SEARCH, color='skyblue', linewidth=3)

plt.show()

# 比特币:搜索热度(右轴)vs 月末价格(左轴)。
# 价格用重采样后的月频数据,才能和月频搜索指数对上。
plt.figure(figsize=(14,8), dpi=120)

plt.title('Bitcoin News Search vs Resampled Price', fontsize=18)
plt.xticks(fontsize=14, rotation=45)

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

ax1.set_ylabel('BTC Price', color='#F08F2E', fontsize=14)
ax2.set_ylabel('Search Trend', color='skyblue', fontsize=14)

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

ax1.set_ylim(bottom=0, top=15000)
ax1.set_xlim([df_btc_monthly.index.min(), df_btc_monthly.index.max()])

# Experiment with the linestyle and markers
ax1.plot(df_btc_monthly.index, df_btc_monthly.CLOSE,
color='#F08F2E', linewidth=3, linestyle='--')
ax2.plot(df_btc_monthly.index, df_btc_search.BTC_NEWS_SEARCH,
color='skyblue', linewidth=3, marker='1')

plt.show()

# 失业金搜索 vs 失业率:两个都是月频,不需要重采样。
# 想看到的是“搜索领先于失业率”还是“同步”。
plt.figure(figsize=(14,8), dpi=120)
plt.title('Monthly Search of "Unemployment Benefits" in the U.S. vs the U/E Rate', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14, rotation=45)

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

ax1.set_ylabel('FRED U/E Rate', color='purple', fontsize=14)
ax2.set_ylabel('Search Trend', color='skyblue', fontsize=14)

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

ax1.set_ylim(bottom=3, top=10.5)
ax1.set_xlim([df_unemployment.MONTH.min(), df_unemployment.MONTH.max()])

# Show the grid lines as dark grey lines
ax1.grid(color='grey', linestyle='--')

# Change the dataset used
ax1.plot(df_unemployment.MONTH, df_unemployment.UNRATE,
color='purple', linewidth=3, linestyle='--')
ax2.plot(df_unemployment.MONTH, df_unemployment.UE_BENEFITS_WEB_SEARCH,
color='skyblue', linewidth=3)

plt.show()

# rolling 滚动平均:ax1.plot(..., 'purple', linewidth=3) 之后接 rolling 版本,
# 把月度噪声压掉,趋势相关性才看得清。
# 同时用 set_major_locator/set_major_formatter 把 x 轴刻度换成按年显示。
plt.figure(figsize=(14,8), dpi=120)
plt.title('Rolling Monthly US "Unemployment Benefits" Web Searches vs UNRATE', fontsize=18)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14, rotation=45)

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

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

ax1.set_ylabel('FRED U/E Rate', color='purple', fontsize=16)
ax2.set_ylabel('Search Trend', color='skyblue', fontsize=16)

ax1.set_ylim(bottom=3, top=10.5)
ax1.set_xlim([df_unemployment.MONTH[0], df_unemployment.MONTH.max()])

# Calculate the rolling average over a 6 month window
roll_df = df_unemployment[['UE_BENEFITS_WEB_SEARCH', 'UNRATE']].rolling(window=6).mean()

ax1.plot(df_unemployment.MONTH, roll_df.UNRATE, 'purple', linewidth=3, linestyle='-.')
ax2.plot(df_unemployment.MONTH, roll_df.UE_BENEFITS_WEB_SEARCH, 'skyblue', linewidth=3)

plt.show()

# 换一份含 2020 年的数据(疫情年份是这张图的关键),同样先转 datetime。
df_ue_2020 = pd.read_csv('UE Benefits Search vs UE Rate 2004-20.csv')
df_ue_2020.MONTH = pd.to_datetime(df_ue_2020.MONTH)

# 终版图:加 2020 年数据后,2020 年 3 月的搜索与失业率同时暴涨 ——
# 这就是“用时间序列讲故事”的落点。
plt.figure(figsize=(14,8), dpi=120)
plt.yticks(fontsize=14)
plt.xticks(fontsize=14, rotation=45)
plt.title('Monthly US "Unemployment Benefits" Web Search vs UNRATE incl 2020', fontsize=18)

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

ax1.set_ylabel('FRED U/E Rate', color='purple', fontsize=16)
ax2.set_ylabel('Search Trend', color='skyblue', fontsize=16)

ax1.set_xlim([df_ue_2020.MONTH.min(), df_ue_2020.MONTH.max()])

ax1.plot(df_ue_2020.MONTH, df_ue_2020.UNRATE, 'purple', linewidth=3)
ax2.plot(df_ue_2020.MONTH, df_ue_2020.UE_BENEFITS_WEB_SEARCH, 'skyblue', linewidth=3)

plt.show()

走读与要点

  1. 四份 CSV 一次读入,shape + head() 逐个检查。
  2. max()/min() 看量级,describe() 一次给出 count/mean/std/min/25%/50%/75%/max。
  3. 缺失值检查:df.isna().values.any()(有没有)、.sum()(有多少个)。比特币价格里有缺失 → dropna(inplace=True)。
  4. df_btc_price[df_btc_price.CLOSE.isna()]:把缺失的那几行打印出来,比只看数字有用(能发现是周末没交易还是抓取失败)。
  5. 四个 to_datetime 一次转完。
  6. resample('M', on='DATE').last() 把日价格压成月价格。
  7. 第一张 Tesla 图:裸双轴 → 加颜色 → 加标题/字号/刻度/网格,是"逐步美化"的示范。

这份代码的问题

(1) 有个空 print

1
print(f'Number of missing values: ')

漏了变量,等于什么都没打印。原意应该是 df_btc_price.isna().values.sum()。

(2) 缺失值那行查错了表

1
print(f'Missing values for BTC price?: {df_btc_search.isna().values.sum()}')

变量名写着 price,用的是 df_btc_search。这种"变量名和内容不一致"的 bug 最隐蔽,因为不报错。

(3) resample('M') 在新版要写 'ME'

pandas 2.2 起 'M' 被弃用(它和"月末"的语义混淆),改成 'ME'(month end)。写 'M' 会警告,未来会报错。

(4) 搜索量是"相对指数"不是绝对次数

Google Trends 返回 0–100 的相对值(相对峰值)。所以"搜索量 100"不代表 100 次搜索,不能和股价做数值比较,只能看趋势同步性。这是这类数据最容易误读的地方。

(5) 双轴图有"视觉操纵"风险

两根轴的缩放比例可以随便调,同一份数据能画出"完全同步"也能画出"毫不相关"。做双轴图必须标清楚两根轴,并且不要故意调范围制造相关性。

运行结果

  • Tesla:股价(红)与搜索热度(蓝)在 2020 年一起暴涨,之后热度先回落、股价继续冲高;
  • Bitcoin:搜索峰值出现在 2017 年底和 2021 年,与价格高点基本同步;
  • Unemployment:2008 金融危机和 2020 疫情期间,搜索量与失业率同步飙升。

易错点

  1. resample 前没设时间索引/没写 on:TypeError: Only valid with DatetimeIndex。
  2. 日数据和月数据直接画在一张图:x 轴点数差 30 倍,线会错位。
  3. mdates 忘了导入:import matplotlib.dates as mdates。
  4. twinx() 后再 plt.plot:画到了 ax1 上,不是 ax2——要用 ax2.plot。

动手改

  • 修掉那个空的 print 和变量名错误。
  • 把 'M' 改成 'ME'。
  • 给比特币图加 marker='o' 和网格。
  • 只看 2020 年之后的区间(df[df.MONTH >= '2020-01-01']),观察疫情的影响。

源文件逐个讲解

6 个文件:

文件 规模 职责
day74.ipynb60 个单元格Google 搜索量 vs 股价/失业率(四个数据集、双轴、滚动平均)
TESLA Search Trend vs Price.csv124 行特斯拉:月度搜索量 + 月末股价
Bitcoin Search Trend.csv73 行比特币:月度新闻搜索量
Daily Bitcoin Price.csv2204 行比特币:每日收盘价 + 成交量
UE Benefits Search vs UE Rate 2004-19.csv181 行失业救济搜索量 vs 失业率(2004–2019)
UE Benefits Search vs UE Rate 2004-20.csv200 行同上,含 2020 年(疫情)

五个 CSV 的结构(真实列名)

(1)TESLA Search Trend vs Price.csv(124 行)

1
2
MONTH,TSLA_WEB_SEARCH,TSLA_USD_CLOSE
2010-06-01,3,4.766000

三列:月份(注意格式是 2010-06-01,带日)、搜索量(整数)、月末收盘价(浮点)。

111 个月的数据(2010-06 到 2020-07)——正好是特斯拉上市后的完整区间。

(2)Bitcoin Search Trend.csv(73 行)

1
2
MONTH,BTC_NEWS_SEARCH
2014-09,5

只有两列,月份格式是 2014-09(不带日)——和特斯拉表不一致。

这是第一个「格式不一致」的坑:pd.to_datetime 都能处理,但合并时要小心。

(3)Daily Bitcoin Price.csv(2204 行)

1
2
DATE,CLOSE,VOLUME
2014-09-17,457.334015,21056800

每日数据——2203 天 ≈ 6 年。

注意列名是 DATE 不是 MONTH——第二个不一致。

(4)两张失业表

1
2
MONTH,UE_BENEFITS_WEB_SEARCH,UNRATE
2004-01,34,5.7

UNRATE 是 FRED(美联储经济数据)的官方代号——失业率,单位 %。

两张表的区别:

文件 行数 搜索量首行
...2004-19.csv18134
...2004-20.csv2009

同样的 2004-01,搜索量一个是 34、一个是 9——这不是笔误,是两个不同版本的导出(Google Trends 每次查询的相对值不同)。

⚠️ 这是本课程一个隐藏的数据质量问题:Google Trends 的数据是「相对指数」(最高点 = 100),换一次查询区间,整条曲线会重标定。所以两张表的搜索量不能直接比较。

day74.ipynb(60 个单元格)

(1)四张表一次读完

1
2
3
4
5
6
df_tesla = pd.read_csv('TESLA Search Trend vs Price.csv')

df_btc_search = pd.read_csv('Bitcoin Search Trend.csv')
df_btc_price = pd.read_csv('Daily Bitcoin Price.csv')

df_unemployment = pd.read_csv('UE Benefits Search vs UE Rate 2004-19.csv')

变量命名很清晰:df_ 前缀 + 内容。

(2)体检:shape / max() / describe()

1
2
3
4
5
6
7
print(df_tesla.shape)
df_tesla.head()

print(f'Largest value for Tesla in Web Search: {df_tesla.TSLA_WEB_SEARCH.max()}')
print(f'Smallest value for Tesla in Web Search: {df_tesla.TSLA_WEB_SEARCH.min()}')

df_tesla.describe()

describe() 一次给出 8 个统计量:count、mean、std、min、25%、50%、75%、max。

这是「一秒钟了解数据分布」的工具——比逐个 max()/min() 高效得多。

注意 describe() 只统计数值列——日期列(MONTH 是字符串)会被跳过。

(3)查缺失值

1
2
3
4
5
6
print(f'Missing values for Tesla?: {df_tesla.isna().values.any()}')
print(f'Missing values for U/E?: {df_unemployment.isna().values.any()}')
print(f'Missing values for BTC Search?: {df_btc_search.isna().values.any()}')

print(f'Missing values for BTC price?: {df_btc_search.isna().values.sum()}')
df_btc_price[df_btc_price.CLOSE.isna()]

三个方法串起来:

  • .isna() → 布尔表
  • .values → numpy 数组
  • .any() / .sum() → 有没有/有几个

这里有一个真 bug**:

1
print(f'Missing values for BTC price?: {df_btc_search.isna().values.sum()}')

变量名写的是 BTC price,但查的是 df_btc_search——查错了表。

下一行 df_btc_price[df_btc_price.CLOSE.isna()] 才查到真正的问题:比特币每日价格里有 1 行 CLOSE 是 NaN。

(4)删缺失

1
df_btc_price.dropna(inplace=True)

inplace=True 原地删除——这次用了原地,没重新赋值。

(5)四张表统一转日期

1
2
3
4
df_tesla.MONTH = pd.to_datetime(df_tesla.MONTH)
df_btc_search.MONTH = pd.to_datetime(df_btc_search.MONTH)
df_unemployment.MONTH = pd.to_datetime(df_unemployment.MONTH)
df_btc_price.DATE = pd.to_datetime(df_btc_price.DATE)

四行,两种列名(三个 MONTH、一个 DATE)——这就是「列名不一致」的代价。

(6)resample:日 → 月

1
df_btc_monthly = df_btc_price.resample('M', on='DATE').last()

这是全书最重要的「时间序列」操作:

resample('M', on='DATE'):按「月」重新分组(M = month end)。

.last():每个月取最后一条——即「月末收盘价」。

三个可选聚合:

聚合 含义
.last()月末价(股价分析常用)
.mean()月均价
.max() / .min()月最高/最低

为什么不能直接和特斯拉表比? 因为比特币表是「天」、特斯拉表是「月」——粒度不同,merge 会错位。必须先 resample 对齐。

on='DATE' 参数:因为 DATE 是「普通列」不是「索引」——如果先 set_index('DATE'),就不用 on=。

(7)register_matplotlib_converters()

1
2
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

这是「消除警告」的一行:

老版本 Matplotlib 不认 Pandas 的 Timestamp,画图时会警告「ConverterRegistration」。注册一下就没了。

新版本(3.5+)已经自动注册,这行变成无害的保险。

(8)日期刻度:YearLocator / MonthLocator / DateFormatter

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

三个「刻度工具」:

对象 作用
YearLocator()每年一个大刻度
MonthLocator()每月一个小刻度
DateFormatter('%Y')把日期显示成 2020

用法(后面几格会用到):

1
2
3
ax1.xaxis.set_major_locator(years)
ax1.xaxis.set_major_formatter(years_fmt)
ax1.xaxis.set_minor_locator(months)

没有它们,x 轴会显示「2010-06-01 12:00:00」这种长串。

(9)特斯拉:搜索量 vs 股价(双轴)

1
2
3
4
5
6
7
8
ax1 = plt.gca() # get current axis
ax2 = ax1.twinx()

ax1.set_ylabel('TSLA Stock Price')
ax2.set_ylabel('Search Trend')

ax1.plot(df_tesla.MONTH, df_tesla.TSLA_USD_CLOSE)
ax2.plot(df_tesla.MONTH, df_tsla.TSLA_WEB_SEARCH)

(最后一行的 df_tsla 是笔误,实际是 df_tesla。)

结构固定:gca() → twinx() → 两个 set_ylabel → 两个 plot。

(10)加颜色

1
2
3
4
5
ax1.set_ylabel('TSLA Stock Price', color='#E6232E') # can use a HEX code
ax2.set_ylabel('Search Trend', color='skyblue') # or a named colour

ax1.plot(df_tesla.MONTH, df_tesla.TSLA_USD_CLOSE, color='#E6232E')
ax2.plot(df_tesla.MONTH, df_tesla.TSLA_WEB_SEARCH, color='skyblue')

两种颜色写法:

  • '#E6232E':十六进制(精确)
  • 'skyblue':命名色(140 个 CSS 颜色名之一)

一致性很重要:左轴标签和左线同色、右轴标签和右线同色——读者一眼能对应。

(11)放大、加标题、加 dpi

1
2
3
4
plt.figure(figsize=(14,8), dpi=120) 
plt.title('Tesla Web Search vs Price', fontsize=18)
...
plt.xticks(fontsize=14, rotation=45)

dpi=120:每英寸 120 点——默认 100,调高图表更清晰(尤其导出 PNG 时)。

rotation=45:日期标签斜着放,避免重叠。

(12)失业率:加网格

1
2
3
plt.title('Monthly Search of "Unemployment Benefits" in the U.S. vs the U/E Rate', fontsize=18)
...
ax1.set_ylabel('FRED U/E Rate', color='purple', fontsize=14)

这一格用了 purple 色——图表主题从红/蓝换成了紫/蓝。

(13)滚动平均:看「谁先动」

1
2
plt.title('Rolling Monthly US "Unemployment Benefits" Web Searches vs UNRATE', fontsize=18)
...

这一格的核心是「6 个月滚动平均」——因为它要回答一个因果问题:

「失业救济」的搜索量,和真实失业率,谁先上升?

搜索量是「人们的担忧」,失业率是「实际结果」——如果搜索量先涨,说明「搜索行为可以预测失业」。

(14)含 2020 的版本

1
2
3
4
df_ue_2020 = pd.read_csv('UE Benefits Search vs UE Rate 2004-20.csv')
df_ue_2020.MONTH = pd.to_datetime(df_ue_2020.MONTH)
...
plt.title('Monthly US "Unemployment Benefits" Web Search vs UNRATE incl 2020', fontsize=18)

这一格是「2020 年疫情的冲击」——失业率在 2020 年 4 月飙到 ~14.7%(历史极值),搜索量也同步暴涨。

为什么单独做一张「含 2020」的表? 因为2020 的数据量级完全盖住了 2004–2019 的波动——画在一起,前面十几年会被压成一条直线。

这是「量级差异」的可视化取舍:要么分开画,要么用对数轴。

(15)set_xlim 锁定 x 轴

1
ax1.set_xlim([df_ue_2020.MONTH.min(), df_ue_2020.MONTH.max()])

set_xlim([起, 止]):锁定 x 轴范围——避免 matplotlib 自动留白。

这份代码的问题

  1. df_btc_search.isna().values.sum() 查错了表(标签写 BTC price)。
  2. df_tsla.TSLA_WEB_SEARCH 变量名笔误(应为 df_tesla)。
  3. 两张失业表的搜索量口径不同(Google Trends 相对值重标定),不能直接比较。
  4. resample('M') 用的是「月末」标签,和 MONTH 列的「月初」标签语义不同——合并时会有 1 个月的错位感。
  5. register_matplotlib_converters() 在新版本已不需要。
  6. dpi=120 + figsize=(14,8) 会让图很大(1680×960 像素),notebook 里显示要滚动。

README.md(8 行)

标题 Day 74 - Google Trends Data: Resampling and Visualising Time Series,知识点:Google Trends、Data Resampling、Visualising Time Series、Matplotlib。

三个关键词正好是这一天的三板斧:

  1. resample:把「日」对齐到「月」;
  2. twinx:两个量纲画在一张图;
  3. rolling:平滑掉噪音看趋势。

这一天的分析方法(「搜索量 vs 现实指标」)是「另类数据」的经典套路——对冲基金真的会用 Google Trends 预测经济。

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