あれもPython,これもPython

Pythonメモ※本サイトはアフィリエイトを利用しています

PandasでWindow関数(移動演算系:移動平均)を再現したい(rolling().*を使う)

前回に引き続き、window関数を再現します。
今回は移動平均などです。 esu-ko.hatenablog.com

SQLで7行移動平均を書く場合は

avg(col) over(order by sort_col rows between 6 preceding and current row)

です。

pandasの場合

import pandas as pd

df.col.rolling(7).mean()

となります。
このばあいは、上記SQLと同じように、7行の最後が演算結果になりますが、その位置を動かす場合、

df.col.rolling(7).mean(center = True)

とします。

その他のもの

rollingの後ろに渡せるものは以下があります。 - sum - std - median - min - max - quantile