2017-08-28 49 views
0

我在想如果有人知道如何在熊貓數據框上實現滾動/移動窗口PCA。我環顧四周,發現在R和MATLAB中的實現,但不是Python。任何幫助,將不勝感激!在熊貓數據框上滾動PCA

這不是重複 - 移動窗口PCA與整個數據幀上的PCA不同。請參閱pandas.DataFrame.rolling(),如果你不理解的差異

+3

太寬了。描述你想要什麼和你的數據框的簡單循環是什麼問題,每個使用sklearn的pca?您提到其他語言的類似工具,但沒有鏈接或任何形式的描述。 – sascha

+1

爲什麼你想要一個滾動的PCA?從統計的角度來看,這是沒有意義的。 – Stergios

+0

您想要滾動平均值或滾動標準偏差的原因相同。基礎數據是時間序列 – Michael

回答

0

不幸的是,pandas.DataFrame.rolling()似乎軋製前拼合df,所以它不能被用來作爲一個可能期望滾過df和傳球的行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的計算值。