在Python中計算移動平均值的方法
前言
在這篇文章中,我們將看到如何在Python中計算移動平均值。移動平均是指總觀測值集合中固定大小子集的一系列平均值。它也被稱為滾動平均。
考慮n個觀測值的集合,k是用于確定任何時間t的平均值的窗口的大小。然后,移動平均列表通過最初取當(dāng)前窗口中存在的前k個觀測值的平均值并將其存儲在列表中來計算?,F(xiàn)在,根據(jù)要確定的移動平均值的條件來擴展窗口,并且再次計算窗口中存在的元素的平均值并將其存儲在列表中。這個過程一直持續(xù)到窗口到達集合的末尾。
例如:給定一個包含五個整數(shù)的列表 arr=[1,2,3,7,9],我們需要計算窗口大小為3的列表的移動平均值。我們將首先計算前3個元素的平均值,并將其存儲為第一個移動平均值。然后窗口將向右移動一個位置,并再次計算窗口中存在的元素的平均值并存儲在列表中。類似地,該過程將重復(fù),直到窗口到達數(shù)組的最后一個元素。以下是對上述方法的說明:

下面是實現(xiàn):
# Program to calculate moving average arr = [1, 2, 3, 7, 9] window_size = 3 i = 0 # Initialize an empty list to store moving averages moving_averages = [] # Loop through the array to consider # every window of size 3 while i < len(arr) - window_size + 1: # Store elements from i to i+window_size # in list to get the current window window = arr[i : i + window_size] # Calculate the average of current window window_average = round(sum(window) / window_size, 2) # Store the average of current # window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
輸出
[2.0, 4.0, 6.33]
簡單移動平均
SMA(Simple Moving Average)的計算方法是取當(dāng)前窗口中某個時間的k個(窗口大?。┯^測值的加權(quán)平均值。它用于分析趨勢。
公式:

其中,
- SMAj = 第j個窗口的簡單移動平均值
- k =窗口大小
- ai =觀測集的第i個元素
方法1:使用Numpy
Python的Numpy模塊提供了一種簡單的方法來計算觀測數(shù)組的簡單移動平均值。它提供了一個名為numpy.sum()的方法,該方法返回給定數(shù)組的元素之和。移動平均值可以通過找到窗口中存在的元素的總和并將其除以窗口大小來計算。
# Program to calculate moving average using numpy import numpy as np arr = [1, 2, 3, 7, 9] window_size = 3 i = 0 # Initialize an empty list to store moving averages moving_averages = [] # Loop through the array t o #consider every window of size 3 while i < len(arr) - window_size + 1: # Calculate the average of current window window_average = round(np.sum(arr[ i:i+window_size]) / window_size, 2) # Store the average of current # window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
輸出
[2.0, 4.0, 6.33]
方法2:使用Pandas
Python的Pandas模塊提供了一種簡單的方法來計算一系列觀測值的簡單移動平均值。它提供了一個名為pandas.Series.rolling(window_size)的方法,該方法返回指定大小的滾動窗口。窗口的平均值可以通過在上面獲得的窗口對象上使用pandas.Series.mean()函數(shù)來計算。pandas.Series.rolling(window_size)將返回一些空序列,因為它至少需要k個(窗口大小)元素才能滾動。
# Python program to calculate # simple moving averages using pandas import pandas as pd arr = [1, 2, 3, 7, 9] window_size = 3 # Convert array of integers to pandas series numbers_series = pd.Series(arr) # Get the window of series # of observations of specified window size windows = numbers_series.rolling(window_size) # Create a series of moving # averages of each window moving_averages = windows.mean() # Convert pandas series back to list moving_averages_list = moving_averages.tolist() # Remove null entries from the list final_list = moving_averages_list[window_size - 1:] print(final_list)
輸出
[2.0, 4.0, 6.33]
累積移動平均
CMA(Cumulative Moving Average)的計算方法是取計算時所有觀測值的加權(quán)平均值。用于時間序列分析。
公式:

其中:
- CMAt = 時間t的累積移動平均值
- kt = 截至?xí)r間t的觀測次數(shù)
- ai = 觀測集的第i個元素
方法1:使用Numpy
Python的Numpy模塊提供了一種簡單的方法來計算觀測數(shù)組的累積移動平均值。它提供了一個名為numpy.cumsum()的方法,該方法返回給定數(shù)組的元素的累積和的數(shù)組。移動平均值可以通過將元素的累積和除以窗口大小來計算。
# Program to calculate cumulative moving average # using numpy import numpy as np arr = [1, 2, 3, 7, 9] i = 1 # Initialize an empty list to store cumulative moving # averages moving_averages = [] # Store cumulative sums of array in cum_sum array cum_sum = np.cumsum(arr); # Loop through the array elements while i <= len(arr): # Calculate the cumulative average by dividing # cumulative sum by number of elements till # that position window_average = round(cum_sum[i-1] / i, 2) # Store the cumulative average of # current window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
輸出
[1.0, 1.5, 2.0, 3.25, 4.4]
方法2:使用Pandas
Python的Pandas模塊提供了一種簡單的方法來計算一系列觀測值的累積移動平均值。它提供了一個名為pandas.Series.expanding()的方法,該方法返回一個窗口,該窗口覆蓋了截至?xí)r間t的所有觀察結(jié)果。窗口的平均值可以通過使用pandas.Series.mean()函數(shù)在上面獲得的窗口對象上計算。
# Python program to calculate # cumulative moving averages using pandas import pandas as pd arr = [1, 2, 3, 7, 9] window_size = 3 # Convert array of integers to pandas series numbers_series = pd.Series(arr) # Get the window of series of # observations till the current time windows = numbers_series.expanding() # Create a series of moving averages of each window moving_averages = windows.mean() # Convert pandas series back to list moving_averages_list = moving_averages.tolist() print(moving_averages_list)
輸出
[1.0, 1.5, 2.0, 3.25, 4.4]
指數(shù)移動平均
EMA(Exponential Moving Average)是通過每次取觀測值的加權(quán)平均值來計算的。觀察值的權(quán)重隨時間呈指數(shù)下降。它用于分析最近的變化。
公式:

其中:
- EMAt = 時間t的指數(shù)移動平均
- α = 觀察權(quán)重隨時間的降低程度
- at = 在時間t的觀察
# Program to calculate exponential # moving average using formula import numpy as np arr = [1, 2, 3, 7, 9] x=0.5 # smoothening factor i = 1 # Initialize an empty list to # store exponential moving averages moving_averages = [] # Insert first exponential average in the list moving_averages.append(arr[0]) # Loop through the array elements while i < len(arr): # Calculate the exponential # average by using the formula window_average = round((x*arr[i])+ (1-x)*moving_averages[-1], 2) # Store the cumulative average # of current window in moving average list moving_averages.append(window_average) # Shift window to right by one position i += 1 print(moving_averages)
輸出
[1, 1.5, 2.25, 4.62, 6.81]
方法1:使用Pandas
Python的Pandas模塊提供了一種簡單的方法來計算一系列觀測值的指數(shù)移動平均值。它提供了一種稱為pandas.Series.ewm.mean()的方法,用于計算給定觀測值的指數(shù)移動平均值。
pandas.Series.ewm()接受一個稱為平滑因子的參數(shù),即觀察值的權(quán)重隨時間減少的程度。平滑因子的值始終介于0和1之間。
# Python program to # calculate exponential moving averages import pandas as pd arr = [1, 2, 3, 7, 9] # Convert array of integers to pandas series numbers_series = pd.Series(arr) # Get the moving averages of series # of observations till the current time moving_averages = round(numbers_series.ewm( alpha=0.5, adjust=False).mean(), 2) # Convert pandas series back to list moving_averages_list = moving_averages.tolist() print(moving_averages_list)
輸出
[1.0, 1.5, 2.25, 4.62, 6.81]
應(yīng)用場景
- 時間序列分析:它用于平滑短期變化并突出長期觀察,如趨勢和周期。
- 金融分析:它用于股票市場的財務(wù)分析,如計算股票價格,回報和分析市場趨勢。
- 環(huán)境工程:它用于分析環(huán)境條件,考慮各種因素,如污染物的濃度等。
- 計算機性能分析:它通過計算平均CPU利用率、平均進程隊列長度等指標來分析計算機性能。
到此這篇關(guān)于在Python中計算移動平均值的方法的文章就介紹到這了,更多相關(guān)Python計算移動平均值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于python實現(xiàn)Pycharm斷點調(diào)試
這篇文章主要介紹了基于python實現(xiàn)Pycharm斷點調(diào)試,在我們寫程序的時候,很容易遇到各種各樣的bug,然后編譯器提示程序出錯的地方。很多時候可以通過提示的信息修改程序,但是有時我們想得到更多的信息,這個時候就需要進行斷點調(diào)試,下面我們就一起來學(xué)習(xí)ycharm斷點調(diào)試2022-02-02
Python實現(xiàn)對字典分別按鍵(key)和值(value)進行排序的方法分析
這篇文章主要介紹了Python實現(xiàn)對字典分別按鍵(key)和值(value)進行排序的方法,結(jié)合實例形式分析了Python基于sorted函數(shù)及operator庫進行字典排序的相關(guān)操作技巧,需要的朋友可以參考下2018-12-12
解決pytorch?model代碼內(nèi)tensor?device不一致的問題
這篇文章主要介紹了pytorch?model代碼內(nèi)tensor?device不一致的問題,本文給大家分享完美解決方案,對pytorch?tensor?device不一致問題解決方案感興趣的朋友跟隨小編一起看看吧2023-07-07

