PythonモジュールPandasで移動平均を計算し、信号データのノイズを低減する方法についてソースコード付きでまとめました。
【例1】近似直線を回帰分析で計算
Pandasで信号データ(CSV)を読み込み、DataFrame.rolling(N).mean()で移動平均を計算してノイズの影響を低減します。
| 種別 | 回読み込んだCSVデータはこちら |
|---|---|
| CSV | current.csv |
サンプルコード
# -*- coding: utf-8 -*-
import os
import ntpath
import joblib
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
# 読み込むCSVファイルのパス
csv_path = "C:/prog/python/auto/current.csv"
# グラフ画像の保存先パス
save_path = "C:/prog/python/auto/"
# 空のデータフレームを作成
df = pd.DataFrame({})
# CSVファイルのロードし、データフレームへ格納
df = pd.read_csv(csv_path, encoding="UTF-8", skiprows=0)
# 電流値の列データを取り出し
Its = df.loc[:, "current"]
# 経過時間の列データを取り出し
times = df.loc[:, "time"]
Its_rm = Its.rolling(10).mean()
# 保存先パスが存在しなければ作成
if not os.path.exists(save_path):
os.mkdir(save_path)
# グラフ化
ax = plt.axes()
plt.rcParams['font.family'] = 'Times New Roman' # 全体のフォント
plt.rcParams['axes.linewidth'] = 1.0 # 軸の太さ
# 電流値をプロット
plt.plot(times, Its, lw=1, c="r", alpha=0.7, ms=2, label="I(t)")
# 電流値をプロット
plt.plot(times, Its_rm, lw=1, c="b", alpha=0.7, ms=2, label="Rm(t)")
# グラフの保存
plt.legend(loc="best") # 凡例の表示(2:位置は第二象限)
plt.xlabel('Time[msec]', fontsize=12) # x軸ラベル
plt.ylabel('Current[A]', fontsize=12) # y軸ラベル
plt.grid() # グリッドの表示
plt.legend(loc="best") # 凡例の表示
plt.savefig(save_path + "current.png")
plt.clf()

| – | 関連記事 |
|---|---|
| 1 | 【Python】Pandasで信号処理入門 |
| 2 | 【Pandas入門】データ分析のサンプル集 |
| 3 | 【Python入門】サンプル集・使い方 |

コメント