重采样和频率转换
重新采样是指将时间序列从一个频率转换为另一个频率的过程。将高频数据聚合到较低频率称为下采样,而将较低频率转换为较高频率称为上采样。并非所有重采样都属于这些类别中的一个。例如,将 W-WED(每周星期三)转换为 W-FRI 既不是上采样也不是下采样。
pandas 对象具有 resample 方法,这是所有频率转换的主要函数。resample 具有与 groupby 类似的 API,调用 resample 对数据进行分组,然后调用聚合函数:
import numpy as np
import pandas as pd
np.random.seed(123456)
dates = pd.date_range("2023-01-01", periods=100)
ts = pd.Series(np.random.standard_normal(len(dates)), index=dates)
# 按月频率重采样,然后求平均
result = ts.resample("ME").mean()
print(result)
result2 = ts.resample("ME", kind="period").mean()
print(result2)
result输出: