首頁  >  文章  >  後端開發  >  如何在Python中對時間序列資料進行重採樣

如何在Python中對時間序列資料進行重採樣

王林
王林轉載
2023-08-29 20:13:05863瀏覽

如何在Python中對時間序列資料進行重採樣

時間序列資料是在固定時間間隔內收集的觀測序列。這些數據可以來自於任何領域,如金融、經濟、健康和環境科學。我們收集的時間序列資料有時可能具有不同的頻率或分辨率,這可能不適合我們的分析和資料建模流程。在這種情況下,我們可以透過上取樣或下取樣來重新取樣時間序列數據,從而改變時間序列的頻率或解析度。本文將介紹不同的方法來上採樣或下採樣時間序列資料。

Upsampling

Upsampling means increasing the frequency of the time series data. This is usually done when we need a higher resolution or more frequent observations. Python provides several methods for upsampling poltimes dataations. Python provids several methods for upsampling poltime s , p圖, interline, interline and polynomial interpolation.

#Syntax

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)

在這裡,

  • #The

    resample function is a method provided by the pandas library to resample time series data. It is applied on a DataFrame and takes the rule parameter, which specifies the desired fquency for takes arguments (*args) and keyword arguments (**kwargs) can be provided to customize the resampling behavior, such as specifying the aggregation method or handling missing values.

## 從

The

asfreq

method is used in conjunction with the resample function to convert the frequency of the time series data. It takes the freq parameter, which specifies the desired frequency string for the output. optional method parameter allows specifying how to handle any missing values introduced during the resampling process, such as forward filling, backward filling, or interpolation.

插值方法用於填滿時間序列資料中的缺失值或間隙。它根據指定的方法(例如'linear'、'nearest'、'spline')進行插值,以估計現有觀測值之間的值。額外的參數可以控制內插的軸,連續NaN值的填滿限制,以及是否在原地修改DataFrame或傳回一個新的DataFrame。

線性內插

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

Example

的中文翻譯為:範例

In the below example, we have a time series DataFrame with three observations on non−consecutive dates. We convert the 'Date' column to a datetime format and set it as the index. The resample function is used to upsa to a daily frequency ('D') using the asfreq method. Finally, the interpolate method with the 'linear' option fills the gaps between the data points using linear interod with the 'linear' option fills the gaps between the data points using linear interpolation. The DataFrame, df_upd .

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

最近鄰插值

Nearest neighbor interpolation is a simple method that fills the gaps between data points with the nearest available observation. This method can be useful when the time series exhibits abrupt method abcan useful when the when series exhibits brupt changes obrupoations inter plates interm. used with the 'nearest' option to perform nearest neighbor interpolation. ### ###Example### 的中文翻譯為:###範例### ###In the above example, we use the same original DataFrame as before. After resampling with the 'D' frequency, the interpolate method with the 'nearest' option fills the gaps by copying the near with the 'nearest' option fills the gaps by copying the nearest available observation. , now has a daily frequency with the nearest neighbor interpolation.###
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提供了不同的降採樣技術,例如在指定的時間間隔內取平均值、總和或最大值。 ### ###Syntax###
DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
###在這裡,聚合方法,如###平均值、和或最大值###,在重新取樣後應用於計算代表每個重新取樣間隔內分組觀測的單一值。這些方法通常在降採樣資料時使用。它們可以直接應用於重新取樣的DataFrame,也可以與重新取樣函數結合使用,根據特定的頻率(如每週或每月),透過指定適當的規則來聚合資料。 ### ###Mean Downsampling###的中文翻譯為:###平均下取樣### ###平均值降採樣計算每個間隔內資料點的平均值。這種方法在處理高頻資料並獲得每個間隔的代表性值時非常有用。可以使用resample函數結合mean方法來執行均值降採樣。 ###

Example

的中文翻译为:

示例

In the below example, we start with a daily time series DataFrame spanning the entire month of June 2023. The resample function with the 'W' frequency downsamples the data to weekly intervals. By applying the mean method, we obtain the average value within each week. The resulting DataFrame, df_downsampled, contains the mean-downsampled time series data.

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

Maximum Downsampling

最大降采样计算并设置每个间隔内的最高值。此方法适用于识别时间序列中的峰值或极端事件。在前面的示例中使用max而不是mean或sum允许我们执行最大降采样。

Example

的中文翻译为:

示例

In the below example, we start with a daily time series DataFrame spanning the entire month of June 2023. The resample function with the 'W' frequency downsamples the data to weekly intervals. By applying the max method, we obtain the Maximum value within each week. The resulting DataFrame, df_downsampled, contains the maximum-downsampled time series data.

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提供了各种上采样和下采样技术。我们探讨了线性和最近邻插值用于上采样,以及均值和最大值插值用于下采样。您可以根据手头的问题使用任何一种上采样或下采样技术。

以上是如何在Python中對時間序列資料進行重採樣的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除