は残念ながら、pandas.DataFrame.rolling()
は、ローリング前df
を平らにするようだ()をpandas.DataFrame.rollingご覧ください。 PCAへの行のウィンドウ。
これは、行ではなくインデックスを転がり回すことに基づいた回避策です。それは非常にエレガントではないかもしれないが、それは動作します:
# Generate some data (1000 time points, 10 features)
data = np.random.random(size=(1000,10))
df = pd.DataFrame(data)
# Set the window size
window = 100
# Initialize an empty df of appropriate size for the output
df_pca = pd.DataFrame(np.zeros((data.shape[0] - window + 1, data.shape[1])))
# Define PCA fit-transform function
# Note: Instead of attempting to return the result,
# it is written into the previously created output array.
def rolling_pca(window_data):
pca = PCA()
transf = pca.fit_transform(df.iloc[window_data])
df_pca.iloc[int(window_data[0])] = transf[0,:]
return True
# Create a df containing row indices for the workaround
df_idx = pd.DataFrame(np.arange(df.shape[0]))
# Use `rolling` to apply the PCA function
_ = df_idx.rolling(window).apply(rolling_pca)
# The results are now contained here:
print df_pca
簡単なチェックは、このことにより、生成された値は、手動で適切な窓をスライスし、それらの上にPCAを実行することによって計算した値を制御するために同一であることが明らかになりました。
これは広すぎます。 sklearnのpcaを使用して、データフレーム上の単純なfor-loopを使って、正確に何を望み、何が間違っているのかを記述します。他の言語でも同様のツールがありますが、リンクや正式な説明はありません。 – sascha
なぜローリングPCAが必要ですか?それは統計的な観点からは意味をなさない。 – Stergios
ローリング平均やローリング標準偏差と同じ理由があります。基礎となるデータは時系列である – Michael