配列 ベクトル 行列 統計

NumPy で配列の移動平均を求める

最終更新日 2023.02.18

NumPy で配列の移動平均を求める関数:

import numpy as np


def moving_average(data, length):
    numbers = []

    for index in range(len(data) - length + 1):
        number = sum(data[index:index + length]) / length
        numbers.append(number)

    return numbers


x = [1, 2, 3, 3, 3, 4, 4, 4, 4]

a = moving_average(x, 2)
b = moving_average(x, 4)

print(a)  # [1.5, 2.5, 3.0, 3.0, 3.5, 4.0, 4.0, 4.0]
print(b)  # [2.25, 2.75, 3.25, 3.5, 3.75, 4.0]