pythonで移動平均

時系列データには,トレンドや季節変動など意味ある成分のほかに,不規則な誤差変動が含まれる場合があります。

こうした非系統的な誤差変動を平滑化するために移動平均が用いられます。

サンプルデータの作成

説明に使用するサンプルデータは以下のコードにより作成しました。

import numpy as np
import pandas as pd

%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Meiryo"

# シードの固定
np.random.seed(0)

# サンプルデータの作成
x = np.linspace(0, 10, 100) * np.pi
y = np.sin(x) + np.random.randn(100) * 0.3  # ノイズ付きサイン波の作成

# サンプルデータの描画
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y, color="blue")
ax.set_ylabel("value")
ax.set_title("ノイズ付きサイン波")
plt.show()

Pandas を用いた処理

DataFrame や Series に対して rolling メソッドを利用し,移動平均を計算します。

後方移動平均の計算

# 後方移動平均の計算
y_rolling = pd.DataFrame(y).rolling(window=12).mean()

後方移動平均結果の描画

# 後方移動平均結果の描画
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y, color="blue", label="原系列")
ax.plot(x, y_rolling.shift(-6), color="red", label="後方移動平均")
ax.set_ylabel("value")
ax.set_title("ノイズ付きサイン波の原系列データと後方移動平均データ")
ax.legend()
plt.show()

中央移動平均の計算

中央移動平均を計算したい場合は center オプションを True に指定します。

# 中央移動平均の計算
y_rolling = pd.Series(y).rolling(window=12, center=True).mean()

中央移動平均結果の描画

# 中央移動平均結果の描画
fig = plt.figure();
ax = fig.add_subplot(1,1,1);
ax.plot(x, y, color="blue", label="原系列")
ax.plot(x, y_rolling, color="red", label="中央移動平均")
ax.set_ylabel("value")
ax.set_title("ノイズ付きサイン波の原系列データと中央移動平均データ")
ax.legend()
plt.show()

その他 Pandas を用いた移動平均計算の詳細については公式ドキュメントを参照のこと。

pandas.DataFrame.rolling — pandas 2.2.3 documentation

Numpy を用いた処理

numpy.convolve を利用して移動平均を計算します。

移動平均の計算

num = 12  # 移動平均を計算する時間窓
roll = np.ones(num) / num  # 移動平均を計算するための配列
y_rolling = np.convolve(y, roll, mode='same')  # 移動平均の計算

移動平均結果の描画

# 移動平均結果の描画
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y, color="blue", label="原系列")
ax.plot(x, y_rolling, color="red", label="移動平均")
ax.set_ylabel("value")
ax.set_title("ノイズ付きサイン波の原系列データと移動平均データ")
ax.legend()
plt.show()

その他 numpy.convolve を用いた移動平均計算の詳細については公式ドキュメントを参照のこと。

numpy.convolve — NumPy v2.3.dev0 Manual

コメント