Pandas 如何使用asfreq()方法对时间序列进行上采样

Pandas 如何使用asfreq()方法对时间序列进行上采样

通过使用pandas的asfreq()方法,我们可以对时间序列进行上采样,并且可以使用fill_value参数填充Nan值。

pandas.Series.asfreq()方法用于将时间序列转换为指定的频率。结果将返回一个重新索引的时间序列,其具有指定的频率。

让我们使用pandas date_range模块创建一个时间序列对象,并使用pandas.series.asfreq()方法对其进行上采样。

示例1

import pandas as pd

# creating dates
date = pd.date_range("2021-07-01", periods=2, freq="M")

# creating pandas Series with date range index
s = pd.Series([5, 6], index=date)
print(s)

# upsample the Timeseries with fill value
print("Output of 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

# create the index
index = pd.date_range('2021-07-1', periods=5, freq='T')

#creating pandas Series with date index
series = pd.Series([2,3,None,4,5], index=index)

print(series)

# upsample the Timeseries with fill value
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个周期,频率为“30s”。

在pandas.Series.asfreq()方法中,fill_value参数不会填充已经存在于给定时间序列对象中的NaN或缺失值。这就是为什么上采样的序列对象中存在NaN值的原因。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程

Pandas 精选笔记