如何计算 NumPy 数组的滚动/移动窗口平均值

计算 NumPy 数组移动平均的最佳方法是使用 bottleneck 中的 bn.move_mean()。首先,使用以下命令安装 bottleneck

install_bottleneck.sh
pip install bottleneck

现在使用以下方式导入

import_bottleneck.sh
import bottleneck as bn

现在你必须决定如何处理数组开头没有足够元素的窗口。默认行为是将这些窗口的结果设置为 NaN

moving_average_examples.py
x = [1,2,3,4,5,6]
result = bn.move_mean(x, window=3)
# result = [nan, nan,  2.,  3.,  4.,  5.]

但你也可以接受任何窗口,即使它少于 window 个元素。

moving_average_min_count.py
x = [1,2,3,4,5,6]
result = bn.move_mean(x, window=3, min_count=1)
# result = [1. , 1.5, 2. , 3. , 4. , 5. ]

另一个使用 window=4 的示例:

moving_average_window4.py
x = [1,2,3,4,5,6]
result = bn.move_mean(x, window=4, min_count=1)
# result = array([1. , 1.5, 2. , 2.5, 3.5, 4.5])

Check out similar posts by category: Python