如何使用 asfreq() 方法对时间序列进行上采样?
pandasserver side programmingprogramming更新于 2025/5/18 9:22:17
通过使用 pandas asfreq() 方法,我们可以对时间序列进行上采样,还可以使用 fill_value 参数填充 Nan 值。
pandas.Series.asfreq() 方法用于将时间序列转换为指定的频率。结果,它将返回具有指定频率的重新索引时间序列。
让我们使用 pandas date_range 模块创建一个时间序列对象,并使用 pandas.series.asfreq() 方法对其进行上采样。
示例 1
import pandas as pd
# 创建日期
date = pd.date_range("2021-07-01", periods=2, freq="M")
# 创建具有日期范围索引的 pandas 系列
s = pd.Series([5, 6], index=date)
print(s)
# 使用填充值对时间序列进行上采样
print("输出asfreq:",s.asfreq(freq='D',fill_value=5))
解释
在下面的例子中,我们使用 pandas date_range 函数创建了一个 pandas 时间序列对象。然后我们将时间序列从月份上采样为"D"天频率,并用标量"5"填充缺失值。
输出
2021-07-31 5 2021-08-31 6 Freq: M, dtype: int64 Output of asfreq: 2021-07-31 5 2021-08-01 5 2021-08-02 5 2021-08-03 5 2021-08-04 5 2021-08-05 5 2021-08-06 5 2021-08-07 5 2021-08-08 5 2021-08-09 5 2021-08-10 5 2021-08-11 5 2021-08-12 5 2021-08-13 5 2021-08-14 5 2021-08-15 5 2021-08-16 5 2021-08-17 5 2021-08-18 5 2021-08-19 5 2021-08-20 5 2021-08-21 5 2021-08-22 5 2021-08-23 5 2021-08-24 5 2021-08-25 5 2021-08-26 5 2021-08-27 5 2021-08-28 5 2021-08-29 5 2021-08-30 5 2021-08-31 6 Freq: D, dtype: int64
初始时间序列由 2 个周期创建,频率为月。之后,我们使用 asfreq() 方法将该时间序列对象上采样为"D"日频率。生成的时间序列有 32 个周期,标量值为"5"。
示例 2
import pandas as pd
# 创建索引
index = pd.date_range('2021-07-1', periods=5, freq='T')
# 创建带有日期索引的 pandas 序列
series = pd.Series([2,3,None,4,5], index=index)
print(series)
# 使用填充值对时间序列进行上采样
print("Converted time series",series.asfreq(freq='30s',fill_value=1))
解释
在此上面的例子中,我们使用 Date_range 方法创建了一个 pandas 时间序列,它有 5 个时间段"T"频率。之后,我们使用 asfreq() 方法将系列对象的频率更改为"30s",这个过程称为上采样。
输出
2021-07-01 00:00:00 2.0 2021-07-01 00:01:00 3.0 2021-07-01 00:02:00 NaN 2021-07-01 00:03:00 4.0 2021-07-01 00:04:00 5.0 Freq: T, dtype: float64 Converted time series 2021-07-01 00:00:00 2.0 2021-07-01 00:00:30 1.0 2021-07-01 00:01:00 3.0 2021-07-01 00:01:30 1.0 2021-07-01 00:02:00 NaN 2021-07-01 00:02:30 1.0 2021-07-01 00:03:00 4.0 2021-07-01 00:03:30 1.0 2021-07-01 00:04:00 5.0 Freq: 30S, dtype: float64
在上面的输出块中,我们可以看到初始时间序列对象和上采样时间序列对象。上采样时间序列对象有 9 个周期,频率为"30 秒"。
pandas.Series.asfreq() 方法中的 fill_value 参数不会填充给定时间序列对象中已经存在的 Nan 或缺失值。这就是上采样序列对象中存在 Nan 值的原因。

