# Python 中 NumPy 数组的滑动平均值

Manav Narula 2023年1月30日

## 使用 `numpy.convolve` 方法来计算 NumPy 数组的滑动平均值

`convolve()` 函数用于信号处理，可以返回两个数组的线性卷积。每个步骤要做的是取一个数组与当前窗口之间的内积并取它们的总和。

``````import numpy as np

def moving_average(x, w):
return np.convolve(x, np.ones(w), "valid") / w

data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])

print(moving_average(data, 4))
``````

``````[ 8.    9.25 13.5  18.   18.5  18.5  17.   15.   14.  ]
``````

## 使用 `scipy.convolve` 方法来计算 NumPy 数组的滑动平均值

``````def moving_average(a, n):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1 :] / n

data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])

print(moving_average(data, 4))
``````

``````[ 8.    9.25 13.5  18.   18.5  18.5  17.   15.   14.  ]
``````

## 使用 `bottleneck` 模块计算滑动平均值

`bottleneck` 模块是快速的 numpy 方法的编译。该模块具有 `move_mean()` 函数，该函数可以返回某些数据的滑动平均值。

``````import bottleneck as bn
import numpy as np

def rollavg_bottlneck(a, n):
return bn.move_mean(a, window=n, min_count=None)

data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])

print(rollavg_bottlneck(data, 4))
``````

``````[  nan   nan   nan  8.    9.25 13.5  18.   18.5  18.5  17.   15.   14.  ]
``````

## 使用 `pandas` 模块计算滑动平均值

``````import pandas as pd
import numpy as np

data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])

d = pd.Series(data)

print(d.rolling(4).mean())
``````

``````0       NaN
1       NaN
2       NaN
3      8.00
4      9.25
5     13.50
6     18.00
7     18.50
8     18.50
9     17.00
10    15.00
11    14.00
dtype: float64
``````

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.