如何使用 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 值的原因。

更新於: 2022年3月9日

256 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.