在Python中計(jì)算移動平均值的方法
前言
在這篇文章中,我們將看到如何在Python中計(jì)算移動平均值。移動平均是指總觀測值集合中固定大小子集的一系列平均值。它也被稱為滾動平均。
考慮n個(gè)觀測值的集合,k是用于確定任何時(shí)間t的平均值的窗口的大小。然后,移動平均列表通過最初取當(dāng)前窗口中存在的前k個(gè)觀測值的平均值并將其存儲在列表中來計(jì)算?,F(xiàn)在,根據(jù)要確定的移動平均值的條件來擴(kuò)展窗口,并且再次計(jì)算窗口中存在的元素的平均值并將其存儲在列表中。這個(gè)過程一直持續(xù)到窗口到達(dá)集合的末尾。
例如:給定一個(gè)包含五個(gè)整數(shù)的列表 arr=[1,2,3,7,9],我們需要計(jì)算窗口大小為3的列表的移動平均值。我們將首先計(jì)算前3個(gè)元素的平均值,并將其存儲為第一個(gè)移動平均值。然后窗口將向右移動一個(gè)位置,并再次計(jì)算窗口中存在的元素的平均值并存儲在列表中。類似地,該過程將重復(fù),直到窗口到達(dá)數(shù)組的最后一個(gè)元素。以下是對上述方法的說明:
下面是實(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)的計(jì)算方法是取當(dāng)前窗口中某個(gè)時(shí)間的k個(gè)(窗口大?。┯^測值的加權(quán)平均值。它用于分析趨勢。
公式:
其中,
- SMAj = 第j個(gè)窗口的簡單移動平均值
- k =窗口大小
- ai =觀測集的第i個(gè)元素
方法1:使用Numpy
Python的Numpy模塊提供了一種簡單的方法來計(jì)算觀測數(shù)組的簡單移動平均值。它提供了一個(gè)名為numpy.sum()的方法,該方法返回給定數(shù)組的元素之和。移動平均值可以通過找到窗口中存在的元素的總和并將其除以窗口大小來計(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模塊提供了一種簡單的方法來計(jì)算一系列觀測值的簡單移動平均值。它提供了一個(gè)名為pandas.Series.rolling(window_size)的方法,該方法返回指定大小的滾動窗口。窗口的平均值可以通過在上面獲得的窗口對象上使用pandas.Series.mean()函數(shù)來計(jì)算。pandas.Series.rolling(window_size)將返回一些空序列,因?yàn)樗辽傩枰猭個(gè)(窗口大?。┰夭拍軡L動。
# 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)的計(jì)算方法是取計(jì)算時(shí)所有觀測值的加權(quán)平均值。用于時(shí)間序列分析。
公式:
其中:
- CMAt = 時(shí)間t的累積移動平均值
- kt = 截至?xí)r間t的觀測次數(shù)
- ai = 觀測集的第i個(gè)元素
方法1:使用Numpy
Python的Numpy模塊提供了一種簡單的方法來計(jì)算觀測數(shù)組的累積移動平均值。它提供了一個(gè)名為numpy.cumsum()的方法,該方法返回給定數(shù)組的元素的累積和的數(shù)組。移動平均值可以通過將元素的累積和除以窗口大小來計(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模塊提供了一種簡單的方法來計(jì)算一系列觀測值的累積移動平均值。它提供了一個(gè)名為pandas.Series.expanding()的方法,該方法返回一個(gè)窗口,該窗口覆蓋了截至?xí)r間t的所有觀察結(jié)果。窗口的平均值可以通過使用pandas.Series.mean()函數(shù)在上面獲得的窗口對象上計(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ù)移動平均
EMA(Exponential Moving Average)是通過每次取觀測值的加權(quán)平均值來計(jì)算的。觀察值的權(quán)重隨時(shí)間呈指數(shù)下降。它用于分析最近的變化。
公式:
其中:
- EMAt = 時(shí)間t的指數(shù)移動平均
- α = 觀察權(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模塊提供了一種簡單的方法來計(jì)算一系列觀測值的指數(shù)移動平均值。它提供了一種稱為pandas.Series.ewm.mean()的方法,用于計(jì)算給定觀測值的指數(shù)移動平均值。
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)用場景
- 時(shí)間序列分析:它用于平滑短期變化并突出長期觀察,如趨勢和周期。
- 金融分析:它用于股票市場的財(cái)務(wù)分析,如計(jì)算股票價(jià)格,回報(bào)和分析市場趨勢。
- 環(huán)境工程:它用于分析環(huán)境條件,考慮各種因素,如污染物的濃度等。
- 計(jì)算機(jī)性能分析:它通過計(jì)算平均CPU利用率、平均進(jìn)程隊(duì)列長度等指標(biāo)來分析計(jì)算機(jī)性能。
到此這篇關(guān)于在Python中計(jì)算移動平均值的方法的文章就介紹到這了,更多相關(guān)Python計(jì)算移動平均值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python?pycharm中使用opencv時(shí)沒有代碼自動補(bǔ)全提示的解決方案
我們在使用pycharm的時(shí)候總是很喜歡其強(qiáng)大的代碼提示功能,下面這篇文章主要給大家介紹了關(guān)于python?pycharm中使用opencv時(shí)沒有代碼自動補(bǔ)全提示的解決方案,需要的朋友可以參考下2022-09-09Windows下Python的Django框架環(huán)境部署及應(yīng)用編寫入門
這篇文章主要介紹了Windows下Python的Django框架環(huán)境部署及程序編寫入門,Django在Python的框架中算是一個(gè)重量級的MVC框架,本文將從程序部署開始講到hellow world web應(yīng)用的編寫,需要的朋友可以參考下2016-03-03python實(shí)現(xiàn)csdn全部博文下載并轉(zhuǎn)PDF
我們學(xué)習(xí)編程,在學(xué)習(xí)的時(shí)候,會有想把有用的知識點(diǎn)保存下來,我們可以把知識點(diǎn)的內(nèi)容爬下來轉(zhuǎn)變成pdf格式,方便我們拿手機(jī)可以閑時(shí)翻看,是很方便的,本文就介紹一下如何實(shí)現(xiàn)2021-06-06node.js獲取參數(shù)的常用方法(總結(jié))
下面小編就為大家?guī)硪黄猲ode.js獲取參數(shù)的常用方法(總結(jié))。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05python優(yōu)化測試穩(wěn)定性的失敗重試工具pytest-rerunfailures詳解
筆者在執(zhí)行自動化測試用例時(shí),會發(fā)現(xiàn)有時(shí)候用例失敗并非代碼問題,而是由于服務(wù)正在發(fā)版,導(dǎo)致請求失敗,從而降低了自動化用例的穩(wěn)定性,那該如何增加失敗重試機(jī)制呢?帶著問題我們一起探索2023-10-10