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