如何在Python中重取樣時間序列資料


時間序列資料是在規則間隔內隨時間收集的一系列觀測值。此資料可以來自任何領域,例如金融、經濟、健康和環境科學。我們收集的時間序列資料有時可能具有不同的頻率或解析度,這可能不適合我們的分析和資料建模過程。在這種情況下,我們可以透過提高或降低取樣率來重取樣時間序列資料,從而更改時間序列的頻率或解析度。本文將解釋重取樣時間序列資料的不同方法。

上取樣

上取樣是指提高時間序列資料的頻率。當我們需要更高的解析度或更頻繁的觀測值時,通常會這樣做。Python 提供了幾種上取樣時間序列資料的方法,包括 **線性插值、最近鄰插值和多項式插值。**

語法

DataFrame.resample(rule, *args, **kwargs)
DataFrame.asfreq(freq, method=None)
DataFrame.interpolate(method='linear', axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None)

這裡:

  • **resample** 函式是 pandas 庫提供的一種用於重取樣時間序列資料的方法。它應用於 DataFrame 並接受 rule 引數,該引數指定所需的重取樣頻率。可以提供附加引數 (*args) 和關鍵字引數 (**kwargs) 來定製重取樣行為,例如指定聚合方法或處理缺失值。

  • **asfreq** 方法與 resample 函式一起使用,用於轉換時間序列資料的頻率。它接受 freq 引數,該引數指定輸出所需的頻率字串。可選的 method 引數允許指定如何處理重取樣過程中引入的任何缺失值,例如前向填充、後向填充或插值。

  • interpolate 方法用於填充時間序列資料中的缺失值或間隙。它根據指定的方法(例如,“linear”、“nearest”、“spline”)執行插值,以估計現有觀測值之間的值。其他引數允許控制執行插值的軸、要填充的連續 NaN 值的限制以及是否就地修改 DataFrame 或返回新的 DataFrame。

線性插值

線性插值用於上取樣時間序列資料。它透過在資料點之間繪製直線來填充資料點之間的間隙。pandas 庫中的 resample 函式可用於實現線性插值。

示例

在下面的示例中,我們有一個時間序列 DataFrame,其中包含三個在非連續日期上的觀測值。我們將“Date”列轉換為日期時間格式並將其設定為索引。resample 函式用於使用 asfreq 方法將資料上取樣到每日頻率 ('D')。最後,使用 'linear' 選項的 interpolate 方法使用線性插值填充資料點之間的間隙。DataFrame df_upsampled 包含使用插值值上取樣的時間序列資料。

import pandas as pd

# Create a sample time series DataFrame
data = {'Date': ['2023-06-01', '2023-06-03', '2023-06-06'],
        'Value': [10, 20, 30]}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

# Upsample the data using linear interpolation
df_upsampled = df.resample('D').asfreq().interpolate(method='linear')

# Print the upsampled DataFrame
print(df_upsampled)

輸出

                Value
Date                 
2023-06-01  10.000000
2023-06-02  15.000000
2023-06-03  20.000000
2023-06-04  23.333333
2023-06-05  26.666667
2023-06-06  30.000000

最近鄰插值

最近鄰插值是一種簡單的方法,它用最近的可用觀測值填充資料點之間的間隙。當時間序列表現出突變或觀測值的順序很重要時,此方法很有用。pandas 中的 interpolate 方法可以與 'nearest' 選項一起使用以執行最近鄰插值。

示例

在上面的示例中,我們使用與之前相同的原始 DataFrame。使用 'D' 頻率重取樣後,使用 'nearest' 選項的 interpolate 方法透過複製最近的可用觀測值來填充間隙。生成的 DataFrame df_upsampled 現在具有每日頻率和最近鄰插值。

import pandas as pd

# Create a sample time series DataFrame
data = {'Date': ['2023-06-01', '2023-06-03', '2023-06-06'],
        'Value': [10, 20, 30]}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

# Upsample the data using nearest neighbor interpolation
df_upsampled = df.resample('D').asfreq().interpolate(method='nearest')

# Print the upsampled DataFrame
print(df_upsampled)

輸出

            Value
Date             
2023-06-01   10.0
2023-06-02   10.0
2023-06-03   20.0
2023-06-04   20.0
2023-06-05   30.0
2023-06-06   30.0

下采樣

下采樣用於降低時間序列資料的頻率,通常是為了獲得更廣泛的資料檢視或簡化分析。Python 提供不同的下采樣技術,例如在指定的時間間隔內取平均值、總和或最大值。

語法

DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

這裡,聚合方法(例如,**平均值、總和或最大值**)在重取樣後應用,以計算代表每個重取樣間隔內分組觀測值的單個值。這些方法通常在對資料進行下采樣時使用。它們可以直接應用於重取樣的 DataFrame,也可以與 resample 函式組合以根據特定頻率(例如每週或每月)聚合資料,方法是指定相應的規則。

平均值下采樣

平均值下采樣計算每個區間內資料點的平均值。處理高頻資料並獲取每個區間的代表性值時,此方法很有用。resample 函式與平均值方法組合可以使用來執行平均值下采樣。

示例

在下面的示例中,我們從跨越 2023 年 6 月整月的每日時間序列 DataFrame 開始。具有 'W' 頻率的 resample 函式將資料下采樣到每週間隔。透過應用平均值方法,我們獲得了每週內的平均值。生成的 DataFrame df_downsampled 包含平均值下采樣的時間序列資料。

import pandas as pd

# Create a sample time series DataFrame with daily frequency
data = {'Date': pd.date_range(start='2023-06-01', end='2023-06-30', freq='D'),
        'Value': range(30)}
df = pd.DataFrame(data)
df.set_index('Date', inplace=True)

# Downsampling using mean
df_downsampled = df.resample('W').mean()

# Print the downsampled DataFrame
print(df_downsampled)

輸出

            Value
Date             
2023-06-04    1.5
2023-06-11    7.0
2023-06-18   14.0
2023-06-25   21.0
2023-07-02   27.0

最大值下采樣

最大值下采樣計算並設定每個區間內的最高值。此方法適用於識別時間序列中的峰值或極端事件。在前面的示例中使用 max 代替 mean 或 sum 可以執行最大值下采樣。

示例

在下面的示例中,我們從跨越 2023 年 6 月整月的每日時間序列 DataFrame 開始。具有 'W' 頻率的 resample 函式將資料下采樣到每週間隔。透過應用 max 方法,我們獲得了每週內的最大值。生成的 DataFrame df_downsampled 包含最大值下采樣的時間序列資料。

import pandas as pd
# Create a sample time series DataFrame with daily frequency
data = {'Date': pd.date_range(start='2023-06-01', end='2023-06-30', freq='D'),
        'Value': range(30)}
df = pd.DataFrame(data)
df.set_index('Date', inplace=True)

# Downsampling using mean
df_downsampled = df.resample('W').max()

# Print the downsampled DataFrame
print(df_downsampled)

輸出

            Value
Date             
2023-06-04      3
2023-06-11     10
2023-06-18     17
2023-06-25     24
2023-07-02     29

結論

在本文中,我們討論瞭如何使用 Python 重取樣時間序列資料。Python 提供各種上取樣和下采樣技術。我們探討了用於上取樣的線性插值和最近鄰插值,以及用於下采樣的平均值和最大值插值。您可以根據手頭的具體問題使用任何上取樣或下采樣技術。

更新於:2023年7月18日

3K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.