周期性与自相关性分析:温度数据案例研究
立即解锁
发布时间: 2025-09-07 01:56:09 阅读量: 15 订阅数: 50 AIGC 


数据清洗的艺术与实践
### 周期性与自相关性分析:温度数据案例研究
#### 1. 引言
在数据分析中,我们常常期望数据具有周期性行为。特别是在顺序数据中存在多个重叠的周期性时,偏离周期性模式的偏差可能比原始值更具信息价值。本文将通过分析多年前收集的美国科罗拉多州一所房子内外的温度数据,探讨如何识别和分析数据中的周期性,并利用自相关技术发现隐藏的周期模式。
#### 2. 数据概述
- **数据来源**:数据由 Brad Huntting 多年前收集,记录了美国科罗拉多州一所房子内外的温度,一般每 3 分钟记录一次,时间跨度接近一年。
- **数据特点**:室内房间由恒温器调节温度,室外温度有明显的季节性变化。数据存在一些不完美之处,在加载数据集的代码中进行了少量的数据清理和值插补。
#### 3. 数据读取与初步观察
使用 Python 函数读取数据为 Pandas DataFrame,后续分析和可视化使用 R 及其 Tidyverse。
```python
thermo = read_glarp()
start, end = thermo.timestamp.min(), thermo.timestamp.max()
print("Start:", start)
print(" End:", end)
# Fencepost counting includes ends
print(" Days:", 1 + (end.date() - start.date()).days)
```
输出结果:
```
Start: 2003-07-25 16:04:00
End: 2004-07-16 15:28:00
Days: 358
```
查看数据集的几行:
```R
%%R -i thermo
glarp <- as.tibble(thermo)
glarp
```
部分数据展示如下:
| timestamp | basement | lab | livingroom | outside |
|---------------------|----------|-----|------------|---------|
| 2003-07-25 16:04:00 | 24 | 25.2 | 29.8 | 27.5 |
| 2003-07-25 16:07:00 | 24 | 25.2 | 29.8 | 27.3 |
| 2003-07-25 16:10:00 | 24 | 25.2 | 29.8 | 27.3 |
| 2003-07-25 16:13:00 | 24.1 | 25.2 | 29.8 | 27.4 |
| 2003-07-25 16:16:00 | 24.1 | 25.2 | 29.8 | 27.8 |
从数据中可以看出,记录间隔为 3 分钟,且无缺失值,原始数据中的一些明显记录错误已通过插补值清理。
#### 4. 数据可视化与趋势分析
##### 4.1 室外温度可视化
```R
%%R
ggplot(glarp, aes(x=timestamp, y=outside)) +
geom_line() + clean_theme +
ggtitle("Outside temperature over recording interval")
```

从图中可以看出,北半球温度在 7 月比 1 月更温暖,整体趋势中有大量抖动。尽管只有一年的数据,但根据基本的领域知识,我们可以预期其他年份也有类似的年度周期。
##### 4.2 地下室温度可视化
```R
%%R
ggplot(glarp, aes(x=timestamp, y=basement)) +
geom_line() + clean_theme +
ggtitle("Basement temperature over recording interval")
```

地下室的室内温度相对较窄,在 14°C 到 23°C 之间。一些点超出了这个范围,可能反映了房子的加热系统或窗户开启等情况。2003 年 9 月和 10 月左右似乎发生了一些奇怪的事情,可能是加热系统的变化。
#### 5. 基于领域知识的趋势分析
##### 5.1 室外温度年度趋势分析
为了识别意外的温暖或寒冷测量值,我们可以对室外温度的年度模式进行建模。由于年度温度呈周期性变化,且在 2003 年最热的一天到 2004 年最热的一天这个时间段内,温度变化形状类似于抛物线,因此我们使用二阶多项式拟合数据。
```R
%%R
# Model the data as a second order polynomial
year.model <- lm(outside ~ poly(timestamp, 2), data = glarp)
# Display the regression and the data
ggplot(glarp, aes(x=timestamp)) + clean_theme +
geom_line(aes(y = outside), color = "gray") +
geom_line(aes(y = predict(year.model)),
color = "darkred", size = 2) +
ggtitle("Outside temperature versus polynomial fit")
```

从图中可以看出,年度去趋势处理解释了大部分数据变化。我们可以通过从原始数据中减去趋势得到一个新的数据集,以突出测量值的意外程度。
```R
%%R
outside <- glarp[, c("timestamp", "outside")] %>%
add_column(no_seasonal = glarp$outside - predict(year.model))
outside
```
可视化季节去趋势后的温度:
```R
%%R
ggplot(outside, aes(x=timestamp)) +
geom_line(aes(y = no_se
```
0
0
复制全文
相关推荐









