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

下面是實(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]
簡(jiǎn)單移動(dòng)平均
SMA(Simple Moving Average)的計(jì)算方法是取當(dāng)前窗口中某個(gè)時(shí)間的k個(gè)(窗口大小)觀測(cè)值的加權(quán)平均值。它用于分析趨勢(shì)。
公式:

其中,
- SMAj = 第j個(gè)窗口的簡(jiǎn)單移動(dòng)平均值
- k =窗口大小
- ai =觀測(cè)集的第i個(gè)元素
方法1:使用Numpy
Python的Numpy模塊提供了一種簡(jiǎn)單的方法來計(jì)算觀測(cè)數(shù)組的簡(jiǎn)單移動(dòng)平均值。它提供了一個(gè)名為numpy.sum()的方法,該方法返回給定數(shù)組的元素之和。移動(dòng)平均值可以通過找到窗口中存在的元素的總和并將其除以窗口大小來計(jì)算。
# 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模塊提供了一種簡(jiǎn)單的方法來計(jì)算一系列觀測(cè)值的簡(jiǎn)單移動(dòng)平均值。它提供了一個(gè)名為pandas.Series.rolling(window_size)的方法,該方法返回指定大小的滾動(dòng)窗口。窗口的平均值可以通過在上面獲得的窗口對(duì)象上使用pandas.Series.mean()函數(shù)來計(jì)算。pandas.Series.rolling(window_size)將返回一些空序列,因?yàn)樗辽傩枰猭個(gè)(窗口大?。┰夭拍軡L動(dòng)。
# 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]
累積移動(dòng)平均
CMA(Cumulative Moving Average)的計(jì)算方法是取計(jì)算時(shí)所有觀測(cè)值的加權(quán)平均值。用于時(shí)間序列分析。
公式:

其中:
- CMAt = 時(shí)間t的累積移動(dòng)平均值
- kt = 截至?xí)r間t的觀測(cè)次數(shù)
- ai = 觀測(cè)集的第i個(gè)元素
方法1:使用Numpy
Python的Numpy模塊提供了一種簡(jiǎn)單的方法來計(jì)算觀測(cè)數(shù)組的累積移動(dòng)平均值。它提供了一個(gè)名為numpy.cumsum()的方法,該方法返回給定數(shù)組的元素的累積和的數(shù)組。移動(dòng)平均值可以通過將元素的累積和除以窗口大小來計(jì)算。
# 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模塊提供了一種簡(jiǎn)單的方法來計(jì)算一系列觀測(cè)值的累積移動(dòng)平均值。它提供了一個(gè)名為pandas.Series.expanding()的方法,該方法返回一個(gè)窗口,該窗口覆蓋了截至?xí)r間t的所有觀察結(jié)果。窗口的平均值可以通過使用pandas.Series.mean()函數(shù)在上面獲得的窗口對(duì)象上計(jì)算。
# 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ù)移動(dòng)平均
EMA(Exponential Moving Average)是通過每次取觀測(cè)值的加權(quán)平均值來計(jì)算的。觀察值的權(quán)重隨時(shí)間呈指數(shù)下降。它用于分析最近的變化。
公式:

其中:
- EMAt = 時(shí)間t的指數(shù)移動(dòng)平均
- α = 觀察權(quán)重隨時(shí)間的降低程度
- at = 在時(shí)間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模塊提供了一種簡(jiǎn)單的方法來計(jì)算一系列觀測(cè)值的指數(shù)移動(dòng)平均值。它提供了一種稱為pandas.Series.ewm.mean()的方法,用于計(jì)算給定觀測(cè)值的指數(shù)移動(dòng)平均值。
pandas.Series.ewm()接受一個(gè)稱為平滑因子的參數(shù),即觀察值的權(quán)重隨時(shí)間減少的程度。平滑因子的值始終介于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)用場(chǎng)景
- 時(shí)間序列分析:它用于平滑短期變化并突出長(zhǎng)期觀察,如趨勢(shì)和周期。
- 金融分析:它用于股票市場(chǎng)的財(cái)務(wù)分析,如計(jì)算股票價(jià)格,回報(bào)和分析市場(chǎng)趨勢(shì)。
- 環(huán)境工程:它用于分析環(huán)境條件,考慮各種因素,如污染物的濃度等。
- 計(jì)算機(jī)性能分析:它通過計(jì)算平均CPU利用率、平均進(jìn)程隊(duì)列長(zhǎng)度等指標(biāo)來分析計(jì)算機(jī)性能。
到此這篇關(guān)于在Python中計(jì)算移動(dòng)平均值的方法的文章就介紹到這了,更多相關(guān)Python計(jì)算移動(dòng)平均值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于python實(shí)現(xiàn)Pycharm斷點(diǎn)調(diào)試
這篇文章主要介紹了基于python實(shí)現(xiàn)Pycharm斷點(diǎn)調(diào)試,在我們寫程序的時(shí)候,很容易遇到各種各樣的bug,然后編譯器提示程序出錯(cuò)的地方。很多時(shí)候可以通過提示的信息修改程序,但是有時(shí)我們想得到更多的信息,這個(gè)時(shí)候就需要進(jìn)行斷點(diǎn)調(diào)試,下面我們就一起來學(xué)習(xí)ycharm斷點(diǎn)調(diào)試2022-02-02
python實(shí)現(xiàn)雙色球隨機(jī)選號(hào)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)雙色球隨機(jī)選號(hào),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01
Python實(shí)現(xiàn)對(duì)字典分別按鍵(key)和值(value)進(jìn)行排序的方法分析
這篇文章主要介紹了Python實(shí)現(xiàn)對(duì)字典分別按鍵(key)和值(value)進(jìn)行排序的方法,結(jié)合實(shí)例形式分析了Python基于sorted函數(shù)及operator庫進(jìn)行字典排序的相關(guān)操作技巧,需要的朋友可以參考下2018-12-12
使用Python快速進(jìn)行Excel合并的幾種場(chǎng)景
由于工作需要,客戶需要將多個(gè)excel文件合并成一個(gè)excel中,下面這篇文章主要給大家介紹了關(guān)于使用Python快速進(jìn)行Excel合并的幾種場(chǎng)景,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10
?分享4款Python 自動(dòng)數(shù)據(jù)分析神器
這篇文章主要給大家分享的是4款Python 自動(dòng)數(shù)據(jù)分析神器,我給大家分享 4 款常用的EDA工具,它們可以自動(dòng)產(chǎn)出統(tǒng)計(jì)數(shù)據(jù)和圖表,為我們節(jié)省大量時(shí)間,需要的朋友可以參考一下2022-03-03
解決pytorch?model代碼內(nèi)tensor?device不一致的問題
這篇文章主要介紹了pytorch?model代碼內(nèi)tensor?device不一致的問題,本文給大家分享完美解決方案,對(duì)pytorch?tensor?device不一致問題解決方案感興趣的朋友跟隨小編一起看看吧2023-07-07

