在Python中計(jì)算移動(dòng)平均值的方法
前言
在這篇文章中,我們將看到如何在Python中計(jì)算移動(dòng)平均值。移動(dòng)平均是指總觀測(cè)值集合中固定大小子集的一系列平均值。它也被稱為滾動(dòng)平均。
考慮n個(gè)觀測(cè)值的集合,k是用于確定任何時(shí)間t的平均值的窗口的大小。然后,移動(dòng)平均列表通過(guò)最初取當(dāng)前窗口中存在的前k個(gè)觀測(cè)值的平均值并將其存儲(chǔ)在列表中來(lái)計(jì)算?,F(xiàn)在,根據(jù)要確定的移動(dòng)平均值的條件來(lái)擴(kuò)展窗口,并且再次計(jì)算窗口中存在的元素的平均值并將其存儲(chǔ)在列表中。這個(gè)過(guò)程一直持續(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ǔ)在列表中。類似地,該過(guò)程將重復(fù),直到窗口到達(dá)數(shù)組的最后一個(gè)元素。以下是對(duì)上述方法的說(shuō)明:

下面是實(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)單的方法來(lái)計(jì)算觀測(cè)數(shù)組的簡(jiǎn)單移動(dòng)平均值。它提供了一個(gè)名為numpy.sum()的方法,該方法返回給定數(shù)組的元素之和。移動(dòng)平均值可以通過(guò)找到窗口中存在的元素的總和并將其除以窗口大小來(lái)計(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)單的方法來(lái)計(jì)算一系列觀測(cè)值的簡(jiǎn)單移動(dòng)平均值。它提供了一個(gè)名為pandas.Series.rolling(window_size)的方法,該方法返回指定大小的滾動(dòng)窗口。窗口的平均值可以通過(guò)在上面獲得的窗口對(duì)象上使用pandas.Series.mean()函數(shù)來(lái)計(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)單的方法來(lái)計(jì)算觀測(cè)數(shù)組的累積移動(dòng)平均值。它提供了一個(gè)名為numpy.cumsum()的方法,該方法返回給定數(shù)組的元素的累積和的數(shù)組。移動(dòng)平均值可以通過(guò)將元素的累積和除以窗口大小來(lái)計(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)單的方法來(lái)計(jì)算一系列觀測(cè)值的累積移動(dòng)平均值。它提供了一個(gè)名為pandas.Series.expanding()的方法,該方法返回一個(gè)窗口,該窗口覆蓋了截至?xí)r間t的所有觀察結(jié)果。窗口的平均值可以通過(guò)使用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)是通過(guò)每次取觀測(cè)值的加權(quán)平均值來(lái)計(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)單的方法來(lái)計(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ī)性能分析:它通過(guò)計(jì)算平均CPU利用率、平均進(jìn)程隊(duì)列長(zhǎng)度等指標(biāo)來(lái)分析計(jì)算機(jī)性能。
到此這篇關(guān)于在Python中計(jì)算移動(dòng)平均值的方法的文章就介紹到這了,更多相關(guān)Python計(jì)算移動(dòng)平均值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python PyYAML庫(kù)解析YAML文件使用詳解
這篇文章主要為大家介紹了Python PyYAML庫(kù)解析YAML文件使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
python?pycharm中使用opencv時(shí)沒(méi)有代碼自動(dòng)補(bǔ)全提示的解決方案
我們?cè)谑褂胮ycharm的時(shí)候總是很喜歡其強(qiáng)大的代碼提示功能,下面這篇文章主要給大家介紹了關(guān)于python?pycharm中使用opencv時(shí)沒(méi)有代碼自動(dòng)補(bǔ)全提示的解決方案,需要的朋友可以參考下2022-09-09
Windows下Python的Django框架環(huán)境部署及應(yīng)用編寫(xiě)入門
這篇文章主要介紹了Windows下Python的Django框架環(huán)境部署及程序編寫(xiě)入門,Django在Python的框架中算是一個(gè)重量級(jí)的MVC框架,本文將從程序部署開(kāi)始講到hellow world web應(yīng)用的編寫(xiě),需要的朋友可以參考下2016-03-03
python中單下劃線_的常見(jiàn)用法總結(jié)
這篇文章主要介紹了python中單下劃線_的常見(jiàn)用法總結(jié),其實(shí)很多(不是所有)關(guān)于下劃線的使用都是一些約定俗成的慣例,而不是真正對(duì)python解釋器有影響,感興趣的朋友跟隨腳本之家小編一起看看吧2018-07-07
python實(shí)現(xiàn)csdn全部博文下載并轉(zhuǎn)PDF
我們學(xué)習(xí)編程,在學(xué)習(xí)的時(shí)候,會(huì)有想把有用的知識(shí)點(diǎn)保存下來(lái),我們可以把知識(shí)點(diǎn)的內(nèi)容爬下來(lái)轉(zhuǎn)變成pdf格式,方便我們拿手機(jī)可以閑時(shí)翻看,是很方便的,本文就介紹一下如何實(shí)現(xiàn)2021-06-06
node.js獲取參數(shù)的常用方法(總結(jié))
下面小編就為大家?guī)?lái)一篇node.js獲取參數(shù)的常用方法(總結(jié))。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05
python優(yōu)化測(cè)試穩(wěn)定性的失敗重試工具pytest-rerunfailures詳解
筆者在執(zhí)行自動(dòng)化測(cè)試用例時(shí),會(huì)發(fā)現(xiàn)有時(shí)候用例失敗并非代碼問(wèn)題,而是由于服務(wù)正在發(fā)版,導(dǎo)致請(qǐng)求失敗,從而降低了自動(dòng)化用例的穩(wěn)定性,那該如何增加失敗重試機(jī)制呢?帶著問(wèn)題我們一起探索2023-10-10

