如何在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)
登入後複製
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.
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)
登入後複製
輸出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
登入後複製
最近鄰插值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
DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
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中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。

在 VS Code 中,可以通過以下步驟在終端運行程序:準備代碼和打開集成終端確保代碼目錄與終端工作目錄一致根據編程語言選擇運行命令(如 Python 的 python your_file_name.py)檢查是否成功運行並解決錯誤利用調試器提升調試效率

VS Code 擴展存在惡意風險,例如隱藏惡意代碼、利用漏洞、偽裝成合法擴展。識別惡意擴展的方法包括:檢查發布者、閱讀評論、檢查代碼、謹慎安裝。安全措施還包括:安全意識、良好習慣、定期更新和殺毒軟件。
