溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python如何實(shí)現(xiàn)滑動(dòng)平均

發(fā)布時(shí)間:2021-04-06 10:50:34 來(lái)源:億速云 閱讀:1416 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下Python如何實(shí)現(xiàn)滑動(dòng)平均,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

Python中滑動(dòng)平均算法(Moving Average)方案:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np

# 等同于MATLAB中的smooth函數(shù),但是平滑窗口必須為奇數(shù)。

# yy = smooth(y) smooths the data in the column vector y ..
# The first few elements of yy are given by
# yy(1) = y(1)
# yy(2) = (y(1) + y(2) + y(3))/3
# yy(3) = (y(1) + y(2) + y(3) + y(4) + y(5))/5
# yy(4) = (y(2) + y(3) + y(4) + y(5) + y(6))/5
# ...

def smooth(a,WSZ):
  # a:原始數(shù)據(jù),NumPy 1-D array containing the data to be smoothed
  # 必須是1-D的,如果不是,請(qǐng)使用 np.ravel()或者np.squeeze()轉(zhuǎn)化 
  # WSZ: smoothing window size needs, which must be odd number,
  # as in the original MATLAB implementation
  out0 = np.convolve(a,np.ones(WSZ,dtype=int),'valid')/WSZ
  r = np.arange(1,WSZ-1,2)
  start = np.cumsum(a[:WSZ-1])[::2]/r
  stop = (np.cumsum(a[:-WSZ:-1])[::2]/r)[::-1]
  return np.concatenate(( start , out0, stop ))

# another one,邊緣處理的不好

"""
def movingaverage(data, window_size):
  window = np.ones(int(window_size))/float(window_size)
  return np.convolve(data, window, 'same')
"""

# another one,速度更快
# 輸出結(jié)果 不與原始數(shù)據(jù)等長(zhǎng),假設(shè)原數(shù)據(jù)為m,平滑步長(zhǎng)為t,則輸出數(shù)據(jù)為m-t+1

"""
def movingaverage(data, window_size):
  cumsum_vec = np.cumsum(np.insert(data, 0, 0)) 
  ma_vec = (cumsum_vec[window_size:] - cumsum_vec[:-window_size]) / window_size
  return ma_vec
"""

以上是“Python如何實(shí)現(xiàn)滑動(dòng)平均”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI