# 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.