我想知道是否有人知道如何在 pandas 数据帧上实现滚动/移动窗口 PCA。我环顾四周,发现 R 和 MATLAB 中有实现,但没有找到 Python。任何帮助,将不胜感激!
这不是重复的 - 移动窗口 PCA 与整个数据帧上的 PCA 不同。如果您不明白其中的区别,请参阅 pandas.DataFrame.rolling()
不幸的是,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
Run Code Online (Sandbox Code Playgroud)
快速检查表明,由此产生的值与通过手动切片适当的窗口并在其上运行 PCA 计算出的控制值相同。