如何利用 Pandas 对时间序列数据进行重采样(Resampling),并填充缺失值(例如使用季节性插值)?

在 Pandas 中,时间序列数据的重采样(Resampling)是通过 `resample` 方法实现的。重采样可以将数据从一个时间频率转换为另一个时间频率(例如从分钟到小时,从小时到天等),并且在转换过程中可能会引入缺失值。为了填充这些缺失值,可以使用多种方法,包括季节性插值(如线性插值、前后填充等)。以下是详细的步骤和示例:

### 1. 数据准备
首先,确保数据包含时间戳索引(`DatetimeIndex`)。如果数据没有时间索引,可以将其转换为时间索引:

```python
import pandas as pd

# 示例数据
data = {'value': [10, 20, 30, 40, 50],
        'date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05']}
df = pd.DataFrame(data)

# 将日期列转换为时间索引
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

2. 重采样

使用 resample 方法对数据进行重采样。例如,将每日数据重采样为每两天的数据:

# 将每日数据重采样为每两天采样一次
resampled = df.resample('2D').mean()
print(resampled)

输出结果可能如下:

            value
date             
2023-01-01   15.0
2023-01-03   35.0
2023-01-05   50.0

注意,resample 后需要使用聚合函数(如 mean、sum)来计算新频率下的值。

3. 填充缺失值

在重采样后,可能会产生缺失值。可以使用 fillna 方法或插值方法(如 interpolate)来填充这些缺失值。以下是几种常见的填充方法:

线性插值

线性插值会根据已知值在时间序列中按线性趋势填充缺失值:

filled = resampled.interpolate(method='linear')
print(filled)

前后填充

如果数据具有明显的季节性,可以使用前向填充(ffill)或后向填充(bfill):

# 前向填充
ffilled = resampled.ffill()

# 后向填充
bfilled = resampled.bfill()

季节性插值

对于具有季节性特征的数据,可以结合 interpolate 方法选择合适的插值方式,例如季节性插值:

# 使用季节性插值
filled = resampled.interpolate(method='time')

4. 实际示例

以下是一个完整的示例,展示如何将每小时的数据重采样为每天的数据,并填充缺失值:

# 创建示例数据(每小时温度)
import numpy as np

rng = pd.date_range('2023-01-01', periods=24, freq='H')
temperature = np.random.randint(10, 30, size=24)
temperature[5:8] = np.nan  # 模拟缺失值
df = pd.DataFrame({'temperature': temperature}, index=rng)

# 重采样为每天的平均值
resampled = df.resample('D').mean()

# 使用季节性插值填充缺失值
filled = resampled.interpolate(method='time')
print(filled)

此代码会将每小时的数据转换为每日数据,并在重采样后使用季节性插值填充缺失值。

5. 注意事项

  • 选择适当的重采样频率和聚合函数非常重要,因为它们会直接影响结果的质量。
  • 插值方法的选择应根据数据的特征(如季节性、趋势性)进行合理决策。
  • 对于复杂的时间序列数据,可能需要结合多种填充方法。

通过这些步骤,可以有效地对时间序列数据进行重采样,并填充缺失值以满足分析和建模的需求。